简体   繁体   English

如何在PrintWriter中删除行

[英]How to Delete Line in PrintWriter

I am writing a program in Java that writes several lines of information into a CSV file. 我正在用Java编写一个程序,该程序将几行信息写入CSV文件。 I want to delete the last line of CSV file, as it is not needed. 我想要删除CSV文件的最后一行,因为不需要。 How would I do this, as the CSV file is created by a PrintWriter, and I don't believe the append method could do this. 我将如何执行此操作,因为CSV文件是由PrintWriter创建的,所以我不相信append方法可以做到这一点。

The extra line is written because the loop continues for one extra line. 之所以写多余的行,是因为循环继续了另外一行。 This portion of the code is as follows: 这部分代码如下:

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();
}
 }

Well, as PrintWriter is just a Writer , which can only append / write / print 好吧,因为PrintWriter只是Writer ,它只能append / write / print
So, you can't override the line which you just have written. 因此,您不能覆盖您刚刚编写的行。
Several options you have : 您有几种选择:

  • Modify your logic to make sure you don't write the line you want to remove eventually (I think the most logical option) 修改逻辑,以确保最终不要删除要删除的行(我认为这是最合逻辑的选择)
  • After writing to file you can use another Reader (say, BufferedReader ) to read it again, and then re-write it, without the line you'd like to exclude. 写入文件后,您可以使用另一个Reader (例如BufferedReader )再次读取它,然后重新写入它,而无需排除行。
  • use RandomAccessFile and its seek method to go back and rewrite / remove the line you need. 使用RandomAccessFile及其seek方法返回并重写/删除所需的行。

You could do the following (this is a way to implement kiruwka's first suggestion): 您可以执行以下操作(这是实现kiruwka的第一个建议的方法):

1) write the first line outside of the while loop. 1)将第一行写在while循环之外。

2) Then for each line written within the while loop first output the newline, and only subsequently output the csv line. 2)然后,对于在while循环中写入的每一行,首先输出换行符,然后才输出csv行。

This way you will have duplicated code, but you won't end up with a newline at the end of the file. 这样,您将具有重复的代码,但不会在文件末尾以换行符结尾。 You can also factor out the duplicate code into a helper method. 您也可以将重复的代码分解为一个辅助方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM