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.

 File csvFile = new File("D:\\Work\\myFolder\\myFile.csv");
 FileWriter fstream = new FileWriter(csvFile.getName(), true);
 BufferedWriter out = new BufferedWriter(fstream);
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);


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

No comments :