I am writing a program in Java that writes several lines of information into a CSV file. I want to delete the last line of CSV file, as it is not needed. 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.

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
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.
  • use RandomAccessFile and its seek method to go back and rewrite / remove the line you need.

其他提示

You could do the following (this is a way to implement kiruwka's first suggestion):

1) write the first line outside of the while loop.

2) Then for each line written within the while loop first output the newline, and only subsequently output the csv line.

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归因
不隶属于 StackOverflow
scroll top