Java 不会使用 FileWriter 写入现有文件

Java won't write to existing file using FileWriter

我想写入 Java 中的文件(我也在 Java 中成功创建)。
我需要向其附加行并按照在线说明操作我的代码应该可以工作。
我从不触发错误(我永远不会到达 catch 块),但我在文本文件中没有得到任何文本。
所有变量都已设置且正确。

这是我的 atm 密码:

private void handleException () {
    String fullPath = logPath + File.separator + logName;
    File logFile = new File(fullPath);
    if (!logFile.exists()) {
        createLogFile(logFile);
    }
    String log = createLog();
    addLogToFile(fullPath, log);
    /*
    if (Bad error of errorlogs > 20 ofazo) {
        alertAdministrator();
    }
    */
}

private void createLogFile(File logFile) {
    try {
        logFile.getParentFile().mkdirs(); //can cause duplicated files in MacOS
        logFile.createNewFile();
    } catch (IOException ex) {
        Logger.getLogger(ErrorHandeling.class.getName()).log(Level.SEVERE, null, ex);
        alertAdministrator("Error while writing logs.\nErrormessage: " + ex.toString());
    }
}

private String createLog() {
    String log = lineCount + ": " + message + "\n occurred in: file=" + writableStackTrace[0].getFileName() + " class=" + writableStackTrace[0].getClassName() + " method=" + writableStackTrace[0].getMethodName() + " line=" + writableStackTrace[0].getLineNumber() + "\n caused by: " + cause.getMessage();
    return log;
}

private void addLogToFile(String fullPath, String log) {
    try {
        FileWriter fw = new FileWriter(fullPath, true);
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter out = new PrintWriter(bw);
        out.println(log);
    } 
    catch (IOException ex) {
        alertAdministrator("Error while writing logs.\nErrormessage: " + ex.toString());
    }
}

检查文档。您正在使用的构造函数:

https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#PrintWriter(java.io.Writer)

明确表示:

Creates a new PrintWriter, without automatic line flushing.

所以不要忘记调用 flush() 方法,close() 编写器一旦完成。

https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#flush() https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#close()

您没有关闭 PrintWriter

但这是糟糕的设计。您应该保持文件打开,而不是每次写入都打开和关闭它。

so don't forget to call the flush() method and close() the writer once done.

感谢jlordo的解决方案,刷新关闭就解决了

But this is poor design. You should keep the file open, not open and close it for every write.

感谢您提供 EJP 信息,我正在刷新文件并保持打开状态,直到程序崩溃或正确关闭