开发者

How to check if a file exists?

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

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

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.

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


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.


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());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜