Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中写入文本文件_Java - Fatal编程技术网

在java中写入文本文件

在java中写入文本文件,java,Java,我有以下写入文件的功能: public void writeToFile(String data) throws IOException { FileWriter fstream = null; try { fstream = new FileWriter("out.txt"); BufferedWriter out = new BufferedWriter(fstream); out.write(data);

我有以下写入文件的功能:

public void writeToFile(String data) throws IOException {
    FileWriter fstream = null;


    try {
        fstream = new FileWriter("out.txt");
        BufferedWriter out = new BufferedWriter(fstream);
        out.write(data);
        //Close the output stream
        out.close();
    } catch (IOException ex) {
        Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            fstream.close();
        } catch (IOException ex) {
            Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

它每次调用时都会创建一个新文件并写入一行。我想要实现的是检查文件是否存在。如果不创建新文件并写入内容,则打开文件并添加新行,而不删除现有文本。怎么做

将FileOutputStream构造函数调用更改为:

fstream = new FileWriter("out.txt", true);

由于java的FileWriter类中有一个构造函数,它可以获得一个bool,如果下一个“条目”被附加到该文件中,则该bool将被IDICATE,因此您应该更改

fstream = new FileWriter("out.txt");

您可以在java文档中查找所有这些构造函数:
FileWriter为appends引入了一个附加参数,用于指定是要创建新文件还是要附加到现有文件

fstream = new FileWriter("out.txt", true);

)

isFile()如果文件存在,则返回true;如果文件不存在,则返回false。或者保存一些代码:
com.google.common.io.Files.append(CharSequence,file,Charset)
+1,无法理解为什么另一个答案的投票数更多,这是一个更好的答案,尽管链接可能会更好
fstream = new FileWriter("out.txt", true);