本文介绍了检查文件存在java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建文本文件,但如果文件已存在,则不应创建新文件,而应将文本附加到现有文件的内容(最后)。我怎么能用Java做呢?

I want create text file but if the file already exists it should not create new file but should append the text to the content (at the end) of the existing file. How can I do it in Java?

我每秒钟都在从输入流读取数据当我停止阅读时我再次开始读取数据我应该写如果文件已存在,则为同一文件

for every one second I'm reading data from inputstream when i stop reading and again i start reading data at that time i should write to same file if file already exist

我是否必须检查条件:

if(file.exists){

} else{
   new File();
}

我需要做什么?

推荐答案

您可以使用以下代码附加到已存在的文件 -

You can use the following code to append to a file which already exists -

try {
    BufferedWriter out = new BufferedWriter(new FileWriter("filename", true));
    out.write("data");
    out.close();
} catch (IOException e) { }

如果构造函数是 true ,然后将字节写入文件的末尾而不是开头。

If the second argument in FileWriter's constructor is true, then bytes will be written to the end of the file rather than the beginning.

引用Stephen的评论:

Quoting Stephen's comment:

这篇关于检查文件存在java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 08:13