Reputation: 149
I'm currently trying to solve this issue where I can't seem to delete the specific content of a csv file.
package projectasdp;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Test {
private static Scanner x;
public static void main(String[] args) {
String filepath = "TradeDetails.txt";
String removeTerm = "3";
removeRecord(filepath, removeTerm);
}
public static void removeRecord(String filepath, String removeTerm) {
String tempFile = "temp.txt";
File oldFile = new File(filepath);
File newFile = new File(tempFile);
String animalID = "";
String seller = "";
String buyer = "";
String wayToTrade = "";
String tradeID = "";
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("[,\r\n]+");
while(x.hasNext()) {
animalID = x.next();
seller = x.next();
buyer = x.next();
wayToTrade = x.next();
tradeID = x.next();
if(!animalID.equals(removeTerm)){
pw.println(animalID + "," + seller + "," + buyer + "," + wayToTrade + "," + tradeID );
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump = new File(filepath);
newFile.renameTo(dump);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error");
}
}
}
CSV:
0,Ann,Jesca,offonline,20180411091801
3,Dave,Dianna,online,20180418105901
6,Dianna,Flynn,offonline,20180418162304
25041019042018,Lex,Ada,online,20180419102911
123456,D,Lucasy,offonline,2018042316230011333,ggg,EEE,online,20190319135223
334,John,Malik,online,20190319135310
The idea here is to delete the all the information of ID 3, which in this case is 3,Dave,Dianna,online,20180418105901
. I have specified it with the removeTerm variable.
So far I haven't managed to get it working and there are other solutions to this problem that I might not be familiar with, so I would really appreciate any help.
Upvotes: 0
Views: 74
Reputation: 6008
The error you get is java.util.NoSuchElementException
while reading the file.
This is caused by the fact 2 lines are concatenated.
2018042316230011333
on the 5th line is interpreted as the traceID.
The next field (ggg) is interpreted as the successive animalID.
Due to this, the last field on the last line is considered a wayToTrade. Then, trying to read the final traceID, you get the error.
Maybe it's better to read the file line by line, split it into its fields and skip the line in case the first field equals the specified removeTerm.
Upvotes: 1