我正在用 Java 编写一个程序,将多行信息写入 CSV 文件中。我想删除 CSV 文件的最后一行,因为不需要它。我该如何执行此操作,因为 CSV 文件是由 PrintWriter 创建的,并且我不相信追加方法可以执行此操作。
之所以会写入额外的一行,是因为循环会继续执行额外的一行。这部分代码如下:
public static void obtainInformation() throws IOException {
PrintWriter docketFile = new PrintWriter(new FileWriter("ForclosureCourtDockets"+startingMonth+"_"+startingDay+"_"+startingYear+"-"+endingMonth+"_"+endingDay+"_"+endingYear+".csv", true));
pageContentString = pageContentString.replace('"','*');
int i = 0;
boolean nextDocket = true;
while(nextDocket) {
nextDocket = false;
String propertyCity = "PropertyCity_"+i+"*>";
Pattern propertyCityPattern = Pattern.compile("(?<="+Pattern.quote(propertyCity)+").*?(?=</span>)");
Matcher propertyCityMatcher = propertyCityPattern.matcher(pageContentString);
while (propertyCityMatcher.find()) {
docketFile.write(i+propertyCityMatcher.group().toString()+", ");
nextDocket = true;
}
String descriptionValue = "Description_"+i+"*>";
Pattern descriptionPattern = Pattern.compile("(?<="+Pattern.quote(descriptionValue)+").*?(?=</span>)");
Matcher descriptionMatcher = descriptionPattern.matcher(pageContentString);
while (descriptionMatcher.find()) {
docketFile.write(descriptionMatcher.group().toString()+"\n");
}
i++;
}
docketFile.close();
}
public static void removeLineFromFile() {
try {
File inFile = new File("ForclosureCourtDockets"+startingMonth+"_"+startingDay+"_"+startingYear+"-"+endingMonth+"_"+endingDay+"_"+endingYear+".csv");
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader("ForclosureCourtDockets"+startingMonth+"_"+startingDay+"_"+startingYear+"-"+endingMonth+"_"+endingDay+"_"+endingYear+".csv"));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals("^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^")) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
最佳答案
嗯,因为 PrintWriter
只是一个 Writer
,它只能 append
/write
/打印
因此,您不能覆盖刚刚编写的行。
您有几个选择:
- 修改您的逻辑,确保您不会编写最终要删除的行(我认为最合乎逻辑的选择)
- 写入文件后,您可以使用另一个
Reader
(例如BufferedReader
)再次读取它,然后重新写入它,而不需要您想要的行排除。 - 使用RandomAccessFile及其
seek
方法返回并重写/删除您需要的行。
关于java - 如何在 PrintWriter 中删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20337200/