Rafael Carrillo
Rafael Carrillo

Reputation: 2883

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)

Upvotes: 3

Views: 14746

Answers (2)

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

Upvotes: 2

ngesh
ngesh

Reputation: 13501

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.

Upvotes: 6

Related Questions