java 如何检查文件是否存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6824987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:25:57  来源:igfitidea点击:

How to check if a file exists?

javaandroid

提问by rafuru

I'm trying to make a method that write a txt plain file on the external memory..

我正在尝试制作一种在外部存储器上写入txt纯文件的方法..

And it works! .. but i want to insert the Date of creation on the footer of the file thorugh the file.exists() method.

它有效!.. 但我想通过 file.exists() 方法在文件的页脚插入创建日期。

If exists doesn't insert date and if not exists insert the date..

如果存在不插入日期,如果不存在则插入日期..

My code is this..

我的代码是这个..

File idea=new File(dir,titulo+".txt");
            FileWriter writer=new FileWriter(idea);
            if (!(idea.exists())){
                texto.append("\n\n\tCreada :"+new Fecha().toString());
            }

Supposing that dir is my path..

假设那个目录是我的路径..

    File dir =new File(Environment.getExternalStorageDirectory(),"/CMI");

and titulo is a parameter that the metod get when is called .. and contains the filename.

而titulo 是method 在被调用时获得的参数.. 并包含文件名。

(Fecha it's my Date class that returns a Date as String)

(Fecha 这是我的 Date 类,它以字符串形式返回日期)

回答by ngesh

File idea=new File(dir,titulo+".txt");
if (!idea.exists()){
    FileWriter writer = new FileWriter(idea);
    texto.append("\n\n\tCreada :" + new Fecha().toString());
    return;
}

Try the above code. If you say FileWriter writer = new FileWriter(idea);it creates a new file if it doesn't exist. So the exist()method doesn't make any difference and always returns true.

试试上面的代码。如果你说它FileWriter writer = new FileWriter(idea);创建一个不存在的新文件。因此该exist()方法没有任何区别并且始终返回true。

回答by Mohammed Azharuddin Shaikh

can you just mould the code

你能塑造一下代码吗

File idea = new File(dir, titulo + ".txt");

if (idea.exists()){
    //do nothing
}
else {
    FileWriter writer=new FileWriter(idea);
    texto.append("\n\n\tCreada :" + new Fecha().toString());
}