java - 如何在 PrintWriter 中删除行

标签 java printwriter writer

我正在用 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/

相关文章:

java - 尝试连接到远程 MySQL 数据库时出现 PacketTooBigException

Python 3 - CSV 阅读器到达文件末尾后,CSV 编写器循环不会关闭

go - 在 Golang 中读取/复制从 `io.Reader` 到 `io.Writer` 的特定数量的字节,或者如果超过特定字节限制则返回错误?

Java PrintWriter 文件覆盖

java - 在 Ldap 搜索上设置方法超时

java - 如何在 JavaFX Canvas 上禁用抗锯齿功能?

java - elasticsearch - 没有为 [查询] 注册的查询]

Java:附加文本文件时跳过用户输入的第一行?

java - 在java中使用JSON读取和写入字符串文件

Java:通过类中的多个方法将文本写入文件而不使用 main() 方法