簡體   English   中英

即使在.flush()/。close()之后,FileWriter也不會寫入文件

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

我試圖寫入一個文本文件,但即使該方法創建該文件,如果它不存在,它不會寫。 我已經通過其他幾個有類似問題的帖子,並按照建議但沒有運氣。

通過使用調試器,String數據包含應該寫入的正確數據,但它永遠不會寫入文本文件。

關於我忽略的事情的任何建議將不勝感激。

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

知道了 - 這就是問題所在:

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

getName()方法只返回bookinginfo.txt ,這意味着它將在當前工作目錄中創建一個名為bookinginfo.txt的文件。

只需使用帶有File的構造函數:

fw = new FileWriter(bookingFile, true);

另請注意,您不需要首先調用createNewFile() - 如果文件不存在, FileWriter構造函數將創建該文件。

另外,我個人不是FileWriter的粉絲 - 它總是使用平台默認編碼。 我建議使用包裝在OutputStreamWriter中的FileOutputStream ,您可以在其中指定編碼。 或者使用Guava輔助方法,使所有這些方法更簡單。 例如:

Files.append(bookingFile, data, Charsets.UTF_8);

用這個

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

代替

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM