嗨,我需要能够删除CSV文件中的一行。我的代码当前删除一行,直到下一行的第一个逗号为止。
我尝试过更改扫描仪定界符,但无法按我的需要来工作。
public void deleteRecord() {
String filePath = "marks.txt";
System.out.println("Enter the StudentID of the record you wish to delete: ");
Scanner in = new Scanner(System.in);
String removeTerm = in.nextLine();
String tempFile = "temp.txt";
File oldFile = new File(filePath);
File newFile = new File(tempFile);
try {
FileWriter fw = new FileWriter(tempFile,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
Scanner scan = new Scanner(oldFile);
scan.useDelimiter("[,]");
while (scan.hasNext()) {
String ID = scan.next();
String Mark = scan.next();
if (!ID.equals(removeTerm)) {
pw.println(ID + "," + Mark);
}
}
scan.close();
pw.flush();
pw.close();
oldFile.delete();
File dump = new File(filePath);
newFile.renameTo(dump);
System.out.println("Record successfully deleted.");
} catch(IOException e) {
System.out.println("Error has occured.");
}
}
B00987,58
B00567,43
B00343,59
B00653,25
B00757,31
B00876,40
B00421,62
B00568,78
B00826,79
B00126,93
B00862,62
B00999,12
B00237,68
B00762,85
B00864,49
这是删除行之前的文件。 我将尝试删除第一行。
43
B00343,59
B00653
25
B00757,31
B00876
40
B00421,62
B00568
78
B00826,79
B00126
93
B00862,62
B00999
12
B00237,68
B00762
85
B00864,49
这就是发生的情况。
我需要它看起来像这样。
B00567,43
B00343,59
B00653,25
B00757,31
B00876,40
B00421,62
B00568,78
B00826,79
B00126,93
B00862,62
B00999,12
B00237,68
B00762,85
B00864,49
有人可以帮我解决这个问题吗?
答案 0 :(得分:3)
您的输入文件每条记录仅包含1个逗号,尽管您扫描了2次以获取ID和标记。因此,第一次扫描会给您ID'B00987'并标记为'58 B00567'。
您可以使用扫描仪并添加多个定界符,如下所示:
s.useDelimiter(",|\\n");
通过这种方式,扫描程序可以扫描到逗号和换行符。
尽管我不经常使用扫描仪,但在您的情况下,我甚至更喜欢使用BufferedReader:
public void deleteRecord() {
String filePath = "marks.txt";
System.out.println("Enter the StudentID of the record you wish to delete: ");
Scanner in = new Scanner(System.in);
String removeTerm = in.nextLine();
String tempFile = "temp.txt";
File oldFile = new File(filePath);
File newFile = new File(tempFile);
try {
FileWriter fw = new FileWriter(tempFile,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
BufferedReader reader = new BufferedReader(new FileReader(oldFile);
String line = "";
while((line = reader.readLine()) != null) {
if(!line.startsWith(removeTerm)) {
pw.println(line);
}
}
reader.close();
pw.flush();
pw.close();
oldFile.delete();
File dump = new File(filePath);
newFile.renameTo(dump);
System.out.println("Record successfully deleted.");
} catch(IOException e) {
System.out.println("Error has occured.");
}
}
也可以使用自动关闭功能或至少适当地管理资源,这是一个不错的优化。