我目前正在尝试解决这个问题,在这里我似乎无法删除csv文件的特定内容。
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
这里的想法是删除ID 3的所有信息,本例中为3,Dave,Dianna,online,20180418105901
。我已经用removeTerm变量指定了它。
到目前为止,我还没有设法使它起作用,还有其他一些我可能不熟悉的解决方案,所以我将非常感谢您的帮助。
答案 0 :(得分:1)
读取文件时遇到的错误是java.util.NoSuchElementException
。
这是由于连接了两行而引起的。
第5行上的2018042316230011333
被解释为traceID。
下一个字段(ggg)被解释为连续的animalID。
因此,最后一行的最后一个字段被认为是wayToTrade。然后,尝试读取最终的traceID,您会收到错误消息。
也许最好逐行读取文件,将其拆分为多个字段,然后跳过该行,以防第一个字段等于指定的removeTerm。