Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java File Writing Randomly stops?

This one's got me going crazy. I have the following code that reads a csv file and re-formats it into a copy paste ready java array format:

  CSVReader reader = new CSVReader(new FileReader(fileName), ',' , '"' , 0);
   FileWriter writer = new FileWriter(outFile);
  //Read CSV line by line and use the string array as you want
  //Read all rows at once
  List<String[]> allRows = reader.readAll();

  //print table header
  //Read CSV line by line and use the string array as you want
 for(String[] row : allRows){
    System.out.println(Arrays.toString(row));
    writer.write("{");
    for(int lcv = 0;lcv<row.length;lcv++){
        if(lcv == row.length -1){
            writer.write(row[lcv]);
        }else{
            writer.write(row[lcv]+",");
        }
    }
    writer.write("},\n");
 }

As you can see, the code prints the records in the file to console, as well as to the file for my copy pasting. The code works, no errors, etc. However, the file created stops randomly halfway through the records. I stepped through code and the write calls are working, and the weirdest part is that the console prints all the records just fine, which SHOULD mirror the file created. Is there anyone that can explain why the file is not finishing but the console is?

More information. The initial file was 76 lines of about 36KB. I thought the issue was that the memory limit was reached as it stopped at line 56 of 76. I re-ran 56-76 (now 1-20) and it stopped at line 18. It's got me stumped...

like image 471
Clint L Avatar asked Jan 22 '15 15:01

Clint L


2 Answers

You probably need to close the FileWriter at the end (and flush for good measure).

for(...) {
   writer.write(row);
}
writer.flush();
writer.close();
like image 68
Todd Avatar answered Oct 20 '22 03:10

Todd


Perhaps you should try to flush the writer ?? You can do it at the end or after each write - usually you do it at the end.

Without flushing explicitly , you rely on the runtime and OS to flsuh things when it feels like it is time to do it. Alternatively, streams get flushed when you close the output stream which you are not doing in the sample code either...

try

writer.flush();

And definitely close things when you are done.

like image 4
Moonwalker Avatar answered Oct 20 '22 02:10

Moonwalker