简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM