I am trying to write to a text file but even though the method creates the file if it does not exist, it does not write. I have been through several other posts with a similar issue and followed the advice but had no luck.
Through use of the debugger, the String data contains the correct data that should be written but it is never written to the text file.
Any advice on something I've overlooked would be appreciated.
private static void createReservation(String filmName, String date, int noOfSeats, String username) {
FileWriter fw = null;
try {
File bookingFile = new File("C:\\server\\bookinginfo.txt");
if (!bookingFile.exists())
{
bookingFile.createNewFile();
}
fw = new FileWriter(bookingFile.getName(),true);
String data = "<"+filmName+"><"+date+"><"+Integer.toString(noOfSeats)+"><"+username+">\r\n";
fw.write(data);
fw.flush();
} catch (IOException ex) {
Logger.getLogger(FilmInfoHandler.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fw.close();
} catch (IOException ex) {
Logger.getLogger(FilmInfoHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Java FileWriter close() Method This method is used to close this FileWriter stream. When we call any of its methods after closing the stream will not result from an exception. This method is available in the java.io package. Closing a writer deallocates any value in it or any resources associated with it.
The FileWriter maintains the file's position and length attributes, so you can seek and write anywhere in the file. By default, the FileWriter writes to the beginning of the file (will overwrite existing data).
FileWriter(File file) : Creates a FileWriter object using specified File object. It throws an IOException if the file exists but is a directory rather than a regular file or does not exist but cannot be created, or cannot be opened for any other reason.
Got it - this is the problem:
new FileWriter(bookingFile.getName(),true);
The getName()
method will just return bookinginfo.txt
, which means it'll be creating a file called bookinginfo.txt
in the current working directory.
Just use the constructor which takes a File
:
fw = new FileWriter(bookingFile, true);
Also note that you don't need to call createNewFile()
first - the FileWriter
constructor will create the file if it doesn't exist.
As an aside, I'm personally not a fan of FileWriter
- it always uses the platform default encoding. I would recommend using FileOutputStream
wrapped in an OutputStreamWriter
where you can specify the encoding. Or use the Guava helper methods which make all of this somewhat simpler. For example:
Files.append(bookingFile, data, Charsets.UTF_8);
Use this
fw = new FileWriter(bookingFile.getAbsolutePath(),true);
instead of
fw = new FileWriter(bookingFile.getName(),true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With