Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file.exists() returning false when the file does exist

In an Android application I'm working on, the user should be able to create a new CSV file on the SD card, named using text they input in an EditText.

The problem is that after instantiating the File using the directory and filename, file.exists() returns false, even when the file does indeed exist at that location. I have browsed to SD card using an Android file browser and through Windows Explorer, and the file does exist.

Is this the correct way to check if the file already exists, and if so, what am I missing so that it returns true when it exists?

String csvname = edittext.getText().toString() + ".csv";
File sdCard = Environment.getExternalStorageDirectory(); //path returns "/mnt/sdcard"
File dir = new File (sdCard.getAbsolutePath() + "/Android/data/" + getPackageName() + "/files/"); // path returns "/mnt/sdcard/Android/data/com.phx.license/files"
dir.mkdirs();
File file = new File(dir, csvname); //path returns "/mnt/sdcard/Android/data/com.phx.license/files/Test.csv"

if(!file.exists()) //WHY DOES IT SAY IT DOESN'T EXIST WHEN IT DOES?
{
    ...
}
like image 241
Gady Avatar asked Mar 25 '11 15:03

Gady


2 Answers

If you use createNewFile it will only create a file if it does not already exist.

Java Files Documentation

public boolean createNewFile() throws IOException Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file. Note: this method should not be used for file-locking, as the resulting protocol cannot be made to work reliably. The FileLock facility should be used instead.

Returns: true if the named file does not exist and was successfully created; false if the named file already exists Throws: IOException - If an I/O error occurred SecurityException - If a security manager exists and its SecurityManager.checkWrite(java.lang.String) method denies write access to the file Since: 1.2

like image 165
Bit Avatar answered Sep 18 '22 01:09

Bit


Creating a new file object like so new File(dir, csvname); does not create a new file in the file system.

You need to write data to it first.

like image 36
jzd Avatar answered Sep 18 '22 01:09

jzd