检查文件存在java [英] check file exists java

查看:95
本文介绍了检查文件存在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) { }

如果 FileWriter的构造函数是 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:


...传递 true ,因为第二个
参数导致文件被创建
如果它不存在并且如果确实存在则打开
进行追加。

...passing true as the 2nd argument causes the file to be created if it doesn't exist and to be opened for appending if it does exist.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆