简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM