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

16,242

Solution 1

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

Solution 2

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.

Share:
16,242

Related videos on Youtube

Gady
Author by

Gady

Software engineer, SF resident, tech/GIS geek, etc

Updated on June 04, 2022

Comments

  • Gady
    Gady almost 2 years

    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?
    {
        ...
    }
    
    • Tahir Akhtar
      Tahir Akhtar about 13 years
      getPackageName() returns same thing every time?
    • Gady
      Gady about 13 years
      @Briedis Yes, the directory exists
    • Gady
      Gady about 13 years
      @ Tahir Akhtar - getPackageName() returns the same thing everytime, since it is always called from the same package
    • Steven Feldman
      Steven Feldman about 13 years
      My suggestion is run it in debugger (or output to console) and see what exactly each of those methods returns.
    • Gady
      Gady about 13 years
      @Steven - I'm using Eclipse and have debugged the heck out of this thing. Watching file.exists(), it always returns false, as does file.getAbsoluteFile().exists().
    • Yoni
      Yoni about 13 years
      perhaps you don't have read permissions on the file? Java's SecurityManager is involved when you call .exists() and it checks the read permissions. Normally if the SecurityManager is enabled, then in this case there will be an exception, not a normal return, but I don't know how it works on Android
    • Erick Robertson
      Erick Robertson about 13 years
      You should really use File.separatorChar instead of hardcoding it with a slash.
    • Gady
      Gady about 13 years
      @Yoni I have added <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> to the manifest file. As far as I know, that's all that is required for the application to access the file system.
    • Gady
      Gady about 13 years
      @Erick - thanks for the suggestion, I'll give it a shot
    • Erick Robertson
      Erick Robertson about 13 years
      @Guddie - that's probably not the problem, but it's good practice.
    • bigstones
      bigstones about 13 years
      Being that the external data directory, be aware that every time you re-install the apk with apt/Eclipse, it will be erased if running on API >= 8. Actually though, I have a 2.2 device (LG Optimus one) and it doesn't happen there, but it does on the emulator.
    • Gady
      Gady about 13 years
      @bigstones You're right, I should probably write the file to a non-application-specific location.
    • MBU
      MBU about 13 years
      why dont you try printing out the file path by using String.valueOf(file) and seeing if the file path is correct. It could be that the file path thats being made by concatenating all the paths together might be wrong. file.exists() shouldn't be returning a wrong result so something else must be wrong.
    • Aleadam
      Aleadam about 13 years
      In adb, issue cd /sdcard; touch testfile and then replace File dir = new File (sdCard.getAbsolutePath()); and String csvname = "testfile"; . Recompile and run. file.exists() should return true now. Post debug results.
    • Sarwar Erfan
      Sarwar Erfan about 13 years
      On the Samsung galaxy S I worked, Environment.getExternalStorageDirectory(); returned the path to the internal flash memory /mnt/sdcard. The real external sd card was mounted on mnt/sdcard/sd. Can this be the issue?
  • Gady
    Gady about 13 years
    My problem is not with creating the file, but checking if it already exists before creating (in this case, overwriting) it.
  • jzd
    jzd about 13 years
    If the file does exist then exists() will return true.
  • Gady
    Gady about 13 years
    The problem is that if I run FileOutputStream f = new FileOutputStream(file); to create the file, it one if it exists, so I don't want to create the file unless it doesn't yet exist.
  • jzd
    jzd about 13 years
    I understand, but if it exists the method will return true. Can you provide an SSCCE where this is not the case? I doubt it, which means your problem is not the exists() it is somewhere else in your code.
  • Gady
    Gady about 13 years
    Then what is the correct usage of File.exists()? What is the purpose of it if not to check if a File object exists?
  • Joe Krill
    Joe Krill about 13 years
    @Guddie -- Are you absolutely sure this file already exists? How do you know? Just creating the file object (new File(..)) does not create the file itself. If File.exists() is returning false, then file just doesn't exist yet. You can create it by calling file.createNewFile().
  • Gady
    Gady about 13 years
    @Joe K - you win! Calling file.createNewFile() creates the file if it doesn't exist, and returns false if it does. Then calling file.exists() after returns true. I believe this is what jzd was trying to say also.
  • Gady
    Gady about 13 years
    @Joe K - Do you mind posting your solution as an answer so I can mark this as answered?
  • Brill Pappin
    Brill Pappin about 11 years
    I'm running into file.exists() == false when I am absolutely sure the file does exist and is a valid file.