Nadeem
Nadeem

Reputation: 63

FileWriter doesn't write to file even after .flush()/.close()

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);
        }
    }
}

Upvotes: 5

Views: 4874

Answers (2)

Jaydeep Rajput
Jaydeep Rajput

Reputation: 3673

Use this

fw = new FileWriter(bookingFile.getAbsolutePath(),true);

instead of

fw = new FileWriter(bookingFile.getName(),true);

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500185

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);

Upvotes: 18

Related Questions