Java – even in flush()/. Filewriter will not write to the file after close()
I tried to write a text file, but even if the method creates the file, if it doesn't exist, it won't write I have passed several other posts with similar problems and followed the suggestions, but I have no luck
Using the debugger, string data contains the correct data that should be written, but it will never be written to a text file
Any advice on what I have overlooked will 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,ex);
}
}
}
Solution
I see – that's the problem:
new FileWriter(bookingFile.getName(),true);
The getname () method only returns bookinginfo Txt, which means that it will create a file called bookinginfo. TXT in the current working directory Txt file
Just use the constructor with file:
fw = new FileWriter(bookingFile,true);
Also note that you do not need to call createnewfile () first – if the file does not exist, the filewriter constructor will create it
In addition, I'm not a fan of filewriter personally - it always uses the platform default encoding I recommend using fileoutputstream wrapped in outputstreamwriter, where you can specify the encoding Or use the guava helper method, which makes all this easier For example:
Files.append(bookingFile,data,Charsets.UTF_8);
