简体   繁体   English

想要使用Java中的PrintWriter类向文件添加行。 文件已创建,数据未保存

[英]Want to add line to file using PrintWriter class in Java. File created, data isn't saved

I want my program to create a new text file unless one already exists. 我希望我的程序创建一个新的文本文件,除非已经存在。 Any way, I want to print one line to the file for each time the program is run. 无论如何,我想每次运行程序时在文件中打印一行。 The file is created but no data is saved to it. 文件已创建,但未保存任何数据。 Why? 为什么?

File fileName = new File("fileName");

try {
    if (fileName.exists())
    {
        filePrinter = new PrintWriter(new FileOutputStream(fileName));
    }
    else
    {
        filePrinter = new PrintWriter(new FileOutputStream(fileName, true));
    }

} catch (FileNotFoundException e1) 
    {
        e1.printStackTrace();
    }

//irrelevant code


filePrinter.println("some text" + integerValue + "then more text");
filePrinter.close();

I would recommend flushing out the content before closing it. 我建议先关闭内容,然后再将其清除。

filePrinter.flush(); 

if this doesnt work try the following: 如果这不起作用,请尝试以下操作:

filePrinter = new FileWriter(new File(fileName));
filePrinter.write("some text" + integerValue + "then more text");
filePrinter.flush();
filePrinter.close();

The problem was outside the posted code, all apologies. 问题出在已发布的代码之外,很抱歉。 The problem was that the 问题是

    //irrelevant code

Contained instructions to reset the program upon certain conditions. 包含在某些条件下重置程序的说明。 Those conditions were always true, and so the filePrinter.println() code was never reached. 这些条件始终是正确的,因此从未达到filePrinter.println()代码。

Thank you for all input. 感谢您的所有投入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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