-5

I'm creating a file with writeToFile() function. Before I call writeToFile() function, I want to check if the file already exist or not. How can I do this?

code:

private void writeToFile(String data, String fileName) {
    try {

        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(this.openFileOutput(fileName, Context.MODE_APPEND));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    }
}
Eric Martinez
  • 31,277
  • 9
  • 92
  • 91

3 Answers3

-1

You could utilize java.io.File and call the .exists() method to check if the file exists.

Use the following code to check if a file already exists.

if(file.exists() && !file.isDirectory()) { 
    // continue code
}
dan14941
  • 332
  • 3
  • 16
-3

Using java.io.File

File f = new File(fileName);
if (f.exists()) { 
    // do something
}

This is a duplicate.

dave
  • 11,641
  • 5
  • 47
  • 65
  • if it's a dupe - why no close-vote? – Jan Jan 01 '16 at 09:57
  • @Jan because I thought marking as duplicate was different to closing and I couldn't see how to do the former. I've now read the manual :) – dave Jan 01 '16 at 22:38
-3
 File file = new File("FileName");
if(file.exists()){
  System.out.println("file is already there");
}else{
   System.out.println("Not find file ");
}

The methods in the Path class are syntactic, meaning that they operate on the Path instance. But eventually you must access the file system to verify that a particular Path exists

Anand Dwivedi
  • 1,452
  • 13
  • 23