This program is almost done. But the problem is when I edit and put it in a temp file, both the edited and unedited values are written. So, the temp file gets another value (which is the replacement). I would also like to know if there are ways on how I could rename the temp file. I tried looking at other questions' answers but none of those solved my problem.
import java.io.*;
import javax.swing.*;
import java.util.*;
public class SecondChild4 extends SecondParent
{
public void editFile(String sFileName, String sFileName2)
{
try
{
sFileName = "Second.csv";
sFileName2 = "Second.txt";
File nfile1 = new File("Second.csv");
File nfile2 = new File("Second.txt");
File file1 = new File("TempSecond.csv");
File file2 = new File("TempSecond.txt");
FileReader reader = new FileReader(sFileName);
FileReader reader2 = new FileReader(sFileName2);
BufferedReader br1 = new BufferedReader(reader);
BufferedReader br2 = new BufferedReader(reader2);
FileWriter twriter = new FileWriter(file1);
FileWriter twriter2 = new FileWriter(file2);
BufferedWriter tbw1 = new BufferedWriter(twriter);
BufferedWriter tbw2 = new BufferedWriter(twriter2);
String edit = "";
String edit2 = "";
String data = "";
Scanner scanner = new Scanner(nfile2);
String _btitle = JOptionPane.showInputDialog (null, "Title: ", "");
String _bauthor = JOptionPane.showInputDialog (null, "Author: ", "");
while(scanner.hasNext()){
boolean replace = false;
String str = scanner.nextLine();
if((str.contains(_btitle))&&(str.contains(_bauthor)))
{
String conv = str.toString();
System.out.println("Search found");
String btitle1 = JOptionPane.showInputDialog (null, "Replace with title: ", "");
String bauthor1 = JOptionPane.showInputDialog (null, "Replace with author: ", "");
edit = str.replaceAll(_btitle, btitle1);
edit2 = str.replaceAll(_bauthor, bauthor1);
tbw1.append(edit);
tbw1.append(",");
tbw1.append(edit2);
tbw1.append("\n");
tbw2.write(edit);
tbw2.write("\t");
tbw2.write(edit2);
tbw2.newLine();
replace = true;
//System.out.println("" +edit + "" +edit2); Test output
}
else {
//System.out.println("" +str); Test output
tbw1.append(str);
tbw1.append("\n");
tbw2.write(str);
tbw2.newLine();
}
}
tbw1.close();
tbw2.close();
br1.close();
br2.close();
nfile1.delete();
file1.renameTo(nfile1);
nfile2.delete();
file2.renameTo(nfile2);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
EDIT 1:
Okay. Figured out how to delete and rename. Problem is I have to edit 2 times before it's finally deleted and renamed. (I removed the author because there are problems with the output).
import java.io.*;
import javax.swing.*;
import java.util.*;
public class SecondChild4 extends SecondParent
{
public void editFile(String sFileName, String sFileName2)
{
try
{
sFileName = "Second.csv";
sFileName2 = "Second.txt";
File nfile1 = new File("Second.csv");
File nfile2 = new File("Second.txt");
File file1 = new File("TempSecond.csv");
File file2 = new File("TempSecond.txt");
FileReader reader = new FileReader(sFileName);
FileReader reader2 = new FileReader(sFileName2);
BufferedReader br1 = new BufferedReader(reader);
BufferedReader br2 = new BufferedReader(reader2);
FileWriter twriter = new FileWriter(file1);
FileWriter twriter2 = new FileWriter(file2);
BufferedWriter tbw1 = new BufferedWriter(twriter);
BufferedWriter tbw2 = new BufferedWriter(twriter2);
String line = "";
String _btitle = JOptionPane.showInputDialog (null, "Title: ", "");
while((line = br2.readLine()) !=null){
String btitle1;
if(line.contains(_btitle))
{
String conv = line.toString();
System.out.println("Search found");
btitle1 = JOptionPane.showInputDialog (null, "Replace with title: ", "");
tbw1.append(line.replaceAll("" +_btitle, "" +btitle1));
tbw1.append("\n");
tbw2.write(line.replaceAll("" +_btitle, "" +btitle1));
tbw2.newLine();
}
else {
tbw1.append(line);
tbw1.append("\n");
tbw2.write(line);
tbw2.newLine();
}
}
twriter.flush();
twriter2.flush();
tbw1.close();
tbw2.close();
br1.close();
br2.close();
nfile1.delete();
file1.renameTo(nfile1);
nfile2.delete();
file2.renameTo(nfile2);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Related
I'm currently testing the edit method for the CSV file. However, the File.Delete() and File.Rename() is highlighting in yellow and told me that these commands will be ignored. What is the cause of this and how do I fix it?
public class Main {
private static Scanner x;
public static void main(String[] args) {
String filepath = "Leads.csv";
String editerm = "Lead_000";
String newID = "Lead_003";
String newname = "Cac";
}
public static void editRecord(String filepath, String editerm, String newID, String newname) {
String tempfile = "temp.csv;";
File oldfile = new File(filepath);
File newfile = new File(tempfile);
String ID = "";
String name = "";
try {
FileWriter fw = new FileWriter(tempfile, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
x = new Scanner(new File(filepath));
x.useDelimiter("[,\n]");
while (x.hasNext()) {
ID = x.next();
name = x.next();
if (ID.equals(editerm)) {
pw.println(newID + "," + newname);
} else {
pw.println(ID + "," + name);
}
x.close();
pw.flush();
pw.close();
oldfile.delete();
File dump = new File(filepath);
newfile.renameTo(dump);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I guess that IDE marks your File.Delete() and File.Rename() lines.
It says that it will ignore the result of this function because you don't store the return value.
If you want to fix it, you should store the return values
boolean result = oldfile.delete();
I am stuck and for the life of me I can't figure out why I am not getting this data to parse out into 5 tokens.
I load the data below in a file called test.dat:
Row1: 1236~~Tier 5~~54~~updated~~01/05/2019
Row2: 1255934~~Tier 1~~30~~Meeting series continued to review period.~~8/21/2018
Row3: 12556~~Tier 1~~30~~Team began to map out Customer Harm Scenarios in this ~~8/21/2018
Row4: 1255936~~Tier 1~~30~~week's calls.
As of now, calls set through August 8th (~~8/21/2018) end of test file.
See how Row 4 in this editor shows the return carriage? In my file it does not have a visible line break like it does here. It must be hidden characters.
This seems to be causing the problem. I tried to remove it, but nothing seems to work.
Here is my code:
import java.io.*;
import java.util.*;
class MergeData {
public static void main(String[] args) {
System.out.print("Enter master_file:");
String master = loadFile();
HashMap masterMap = readData(master);
}
public static String loadFile(){
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String fileName = new String();
try{
fileName = br.readLine();
System.out.print("opening file... "+ fileName+"\n");
}catch(IOException nfe){
System.err.println("Invalid Format!");
}
return fileName;
}
public static HashMap readData(String file){
HashMap dataMap = new HashMap();
try {
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
String line;
int rowCnt = 0;
while ((line = br.readLine()) != null) {
String clean = line.replaceAll("(?:\\n|\\r)", "");
String[] fields = clean.split("~~");
int size = fields.length;
System.out.println("delimiter size:" + size );
rowCnt = rowCnt +1;
String f1 = null;
String f2 = null;
String f3 = null;
String f4 = null;
String f5 = null;
if(size == 5){
f1 = fields[0];
f2 = fields[1];
f3 = fields[2];
f4 = fields[3];
f5 = fields[4];
} else {
System.out.println("!!! INVALID ROW: id---->" + fields[0]);
}
System.out.println(
"rowCnt:" +rowCnt+ " f1:" +f1+ "----f2:" +f2+
"----f3:" +f3+ "----f4:" + f4+ "----f5:" + f5 +"\n\n");
}
br.close();
fileReader.close();
} catch (IOException e) {
System.out.println("\n File Read Error \n" +e );
}
return dataMap;
}
}
I have some CSV file with the same column header.
I want to make them to one file.So I found something similar to me. Link is Merge CSV files into a single file with no repeated headers.
but I want to return the data as a String, but this code has no return.
I try to modify that. but I failed.
I want to put the data from several csv into one variable.
String[] headers = null;
String firstFile = "/path/to/firstFile.dat";
Scanner scanner = new Scanner(new File(firstFile));
if (scanner.hasNextLine())
headers[] = scanner.nextLine().split(",");
scanner.close();
Iterator<File> iterFiles = listOfFilesToBeMerged.iterator();
BufferedWriter writer = new BufferedWriter(new FileWriter(firstFile, true));
while (iterFiles.hasNext()) {
File nextFile = iterFiles.next();
BufferedReader reader = new BufferedReader(new FileReader(nextFile));
String line = null;
String[] firstLine = null;
if ((line = reader.readLine()) != null)
firstLine = line.split(",");
if (!Arrays.equals (headers, firstLine))
throw new FileMergeException("Header mis-match between CSV files: '" +
firstFile + "' and '" + nextFile.getAbsolutePath());
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
reader.close();
}
writer.close();
Here is what you might be looking for.
I have read two csv files and written into one.
Hope this is use full...
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class CombineTwoFile
{
public static void main(String[] args) throws IOException
{
ArrayList<String> list = new ArrayList<String>();
try
{
BufferedReader br = new BufferedReader(new FileReader( "d:\\1\\1.csv"));
BufferedReader r = new BufferedReader(new FileReader( "d:\\1\\2.csv"));
String s1 =null;
String s2 = null;
while ((s1 = br.readLine()) != null)
{
list.add(s1);
}
while((s2 = r.readLine()) != null)
{
list.add(s2);
}
}
catch (IOException e)
{
e.printStackTrace();
}
BufferedWriter writer=null;
writer = new BufferedWriter(new FileWriter("d:\\1\\good.csv"));
String listWord;
for (int i = 0; i< list.size(); i++)
{
listWord = list.get(i);
writer.write(listWord);
writer.write("\n");
}
System.out.println("DONE Enjoy!!");
writer.close();
}
}
Or if you looking for a function which returns String combining two csv
public static String combineCSV() {
ArrayList<String> list = new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader(
"d:\\1\\1.csv"));
BufferedReader r = new BufferedReader(
new FileReader("d:\\1\\2.csv"));
String s1 = null;
String s2 = null;
while ((s1 = br.readLine()) != null) {
list.add(s1);
}
while ((s2 = r.readLine()) != null) {
list.add(s2);
}
} catch (IOException e) {
e.printStackTrace();
}
String listWord;
StringBuffer objBuffer = new StringBuffer();
for (int i = 0; i < list.size(); i++) {
listWord = list.get(i);
objBuffer.append(listWord);
objBuffer.append("\n");
}
System.out.println("DONE Enjoy!!");
System.out.println(objBuffer);
return objBuffer.toString();
}
Thank you!!!!
Enjoy Coding...
Another alternative is to use Open CSV library
My program is basically a user's name, and balance, this is stored in a file, when the user updates their profile, I want their balance to update too, but not their name, as they already have it in the file.
The name and balance are split with a comma. In the file it is displayed like this:
Stacey,0.02
(The name is actually a randomly generated number+letter string, but I thought I'd keep it simple here.)
When I try to write to the file with this code, it doesn't write anything.
Code:
btnSaveUserid.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = txtUserid.getText().toString();
String balance = beedcoin1Balance.getText().toString();
File file = new File("d:/users/joel/desktop/code/usersid.txt");
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("d:/users/joel/desktop/code/usersid.txt"));
List<String> terms = new ArrayList<String>();
List<String> ttlBalance = new ArrayList<String>();
while ((sCurrentLine = br.readLine()) != null) {
String[] ar = sCurrentLine.split(",");
String userid = ar[0];
terms.add(userid);
System.out.println(terms);
}
if(terms.contains(text)) {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("d:/users/joel/desktop/code/usersid.txt")));
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine());
String line = scanner.nextLine();
String[] ar = line.split(",");
String userid = ar[0];
String bdcv1val = ar[1];
int lineNum = 0;
lineNum++;
if(line.equals(userid)) {
Path path = Paths.get("d:/users/joel/desktop/code/usersid.txt");
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
content = content.replace(txtUserid.toString(), txtUserid.toString());
Files.write(path, content.getBytes(charset));
out.println(text + "," + balance);
System.out.println("Successfully printed to usersid.txt");
}
}
else {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("d:/users/joel/desktop/code/usersid.txt")));
out.println(text + "," + balance);
System.out.println("Successfully printed to usersid.txt");
}
} catch (IOException el) {
el.printStackTrace();
} finally {
try {
if(br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
It all takes place in a button's action listener, and this code outputs the "Successfully printed to file" but doesn't actually print it to the file. I'm honestly perplexed, any help would be greatly appreciated.
I have done the reading and writing of the files, but I have a problem. I don't know why it shows only the last line of the files. In the part with reading the lines from Person.txt, when I get out of the while loop, I want to show the p.getName() for each line and it shows only the last line. How can I fix this?
here is my code:
import java.io.*;
import java.util.*;
import java.util.ArrayList;
public class ListaHobby {
String line="";
Hobby h = new Hobby();
Persoana p = new Persoana();
BufferedWriter bw = null;
ArrayList<Persoana> listOfPersons;
ArrayList<Hobby> listOfHobbies;
public void writeListaHobbies(){
try{
listOfPersons = new ArrayList<Persoana>();
FileReader file1 =new FileReader("Persoane.txt");
listOfHobbies = new ArrayList<Hobby>();
FileReader file2 = new FileReader("Hobby.txt");
BufferedReader br1 = new BufferedReader(file1);
BufferedReader br2 = new BufferedReader(file2);
while((line1 = br1.readLine()) != null){
if(!line1.trim().contains("ID")){
String[] attributes = line1.split(";");// split it at every ";"
//Person person = new Person(); // make a new person
p.setNume(attributes[1]);
p.setPrenume(attributes[2]);
p.setDataNasterii(attributes[3]);
p.setProfesie(attributes[4]);
listOfPersons.add(p);
}
}
System.out.println(p.getNume());
while((line2 = br2.readLine()) != null){
if(!line2.trim().contains("ID")){
String[] attributes = line2.split(";"); // split it at every ";"
// make a new person
h.setNume(attributes[1]);
h.setDescriere(attributes[2]);
h.setNrPers(attributes[3]);
h.setElemNecesar(attributes[4]);
listOfHobbies.add(h);
}
}
System.out.println(h.getNume());
FileWriter fw = new FileWriter("PersHobby.txt");
bw = new BufferedWriter(fw);
for(int i = 0;i < listOfPersons.size(); i++) {
//for(int j = 0 ; j < listOfHobbies.size();j++) {
if((p.getId())== (h.getId()))
p.addHobby(h);
String s = p.getNume() + " " +p.getPrenume() +
": " + h.getNume() + ", " + h.getNume();
System.out.println(s);
bw.write(s);
bw.newLine();
}
bw.close();
}
catch(IOException ex){
System.out.println("Error opening file.");
System.exit(1);
}
}
}
You keep adding the same person to your list. You need to create a new object at each iteration by uncommenting the commented line. Once you have done that, you can remove the class member (p) as it is not needed any longer because you store the persons in the ArrayList.
The same comment applies to the list of hobbies.
while((line1 = br1.readLine()) != null){
if(!line1.trim().contains("ID")){
String[] attributes = line1.split(";");// split it at every ";"
Persoana p = new Persoana(); // <~~~ you need to create a new person for each line
p.setNume(attributes[1]);
p.setPrenume(attributes[2]);
p.setDataNasterii(attributes[3]);
p.setProfesie(attributes[4]);
listOfPersons.add(p);
}
}
You are using the single instances of Person and Hobby to add to the respective lists. Instead, for each (unique?) ID found, create new Person, new Hobby and use them to add to the list.
p = new Person();
p.setXXX...
...
Similarly for Hobby.
h = new Hobby();
h.setXXX...
...
Unless you do this, you only be adding the latest found data to the same person and hobby objects to the lists.
You need to add people and hobbies when reading each line of the input file and iterate through both the people and hobbies when writing to file.
import java.io.*;
import java.util.*;
import java.util.ArrayList;
public class ListaHobby {
String line="";
Hobby h;
Persoana p;
BufferedWriter bw = null;
ArrayList<Persoana> listOfPersons;
ArrayList<Hobby> listOfHobbies;
public void writeListaHobbies(){
try{
listOfPersons = new ArrayList<Persoana>();
FileReader file1 =new FileReader("Persoane.txt");
listOfHobbies = new ArrayList<Hobby>();
FileReader file2 = new FileReader("Hobby.txt");
BufferedReader br1 = new BufferedReader(file1);
BufferedReader br2 = new BufferedReader(file2);
while((line1 = br1.readLine()) != null){
if(!line1.trim().contains("ID")){
String[] attributes = line1.split(";");// split it at every ";"
p = new Persoana(); // make a new person
p.setNume(attributes[1]);
p.setPrenume(attributes[2]);
p.setDataNasterii(attributes[3]);
p.setProfesie(attributes[4]);
listOfPersons.add(p);
}
}
System.out.println(p.getNume());
while((line2 = br2.readLine()) != null){
if(!line2.trim().contains("ID")){
String[] attributes = line2.split(";"); // split it at every ";"
h=new Hobby();
h.setNume(attributes[1]);
h.setDescriere(attributes[2]);
h.setNrPers(attributes[3]);
h.setElemNecesar(attributes[4]);
listOfHobbies.add(h);
}
}
System.out.println(h.getNume());
FileWriter fw = new FileWriter("PersHobby.txt");
bw = new BufferedWriter(fw);
for(int i = 0;i < listOfPersons.size(); i++) {
p=listOfPersons.get(i);
for(int j = 0 ; j < listOfHobbies.size();j++) {
h=listOfHobbies.get(j);
if(p.getId())== h.getId()))
p.addHobby(h);
String s = p.getNume() + " " +p.getPrenume() +
": " + h.getNume() + ", " + h.getNume();
System.out.println(s);
bw.write(s);
bw.newLine();
}
}
bw.close();
}
catch(IOException ex){
System.out.println("Error opening file.");
System.exit(1);
}
}
}