Tuesday, July 17, 2012

File I/O with Java

I have started dabbling a bit in Java recently and well you can call it a silly mistake but this problem did ruffle my feathers. I was trying to append the contents of my query data to a file and all of my code as seen below seemed proper.

try
{
 File csvFile = new File("D:\\Work\\myFolder\\myFile.csv");
 if(!csvFile.exists())
 {
  csvFile.createNewFile();
 }
 FileWriter fstream = new FileWriter(csvFile.getName(), true);
 BufferedWriter out = new BufferedWriter(fstream);
 out.write(dataToWrite);
 out.close();
 fstream.close();
}
catch (Exception e)
{
 System.err.println("Error: " + e.getMessage());
} 

But essentially it did not work. The file was created but nothing was written in it. A little while and some research I figured out the problem. 
So basically one needs to either supply the "file" or the complete "filePath" as the parameter to the FileWriter class. Just the name doesn't do it, except if the file resides in the root folder. So we can use either one of the two.
 FileWriter fstream = new FileWriter(csvFile, true);

                                                                   OR

 FileWriter fstream = new FileWriter(csvFile.getPath(), true);

No comments :