eatinasandwich
eatinasandwich

Reputation: 636

Java fileWriter is not writing all of my output to a file

I'm trying to write a quick java program to take a csv and create insert statements in SQL. I don't need all the columns or else I would have just directly imported the data through the csv. My particular problem comes when I actually write out to the file. The writer should be outputting over 200 lines to the file but only does 190 or so. I'm using eclipse and was wondering if eclipse shuts the program down before the IO is done but I'm not sure how to check that. Here is the code that does the writes:

  FileWriter fw = new FileWriter("CountriesOut.csv");
  CSVWriter writer = new CSVWriter(fw);
  for (int i = 0; i < line.size(); i++) {
      fw.write("INSERT INTO Country (CountryID, CountryName, CountryLocation, SummerFirstAppearance, WinterFirstAppearance) VALUES (");
      writer.writeNext(line.get(i));
      fw.write(");\n");
  }

I'm using openCSV to parse and eclipse for an IDE. Also relevant is that it cuts off in the middle of lines so I know its not just terminating at some point during the loop.

Upvotes: 1

Views: 2036

Answers (1)

Stephen C
Stephen C

Reputation: 718906

I'm using eclipse and was wondering if eclipse shuts the program down before the IO is done

Nope.

The problem is that your application exits before it has written all of the data that has been buffered. (This most likely is in a separate JVM to Eclipse, and Eclipse has no hand in this.)

At the end of your application, you should call fw.close().

In addition, it would be advisable to writer.flush() after the writeNext(...) call and before the following fw.write(...). The javadocs for CSVWriter don't say whether or not it does any buffering. If it does, then a flush would be necessary to get the "interleaving" right for the sources of output.

Upvotes: 2

Related Questions