File.exists () returns false when the file exists

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

The problem is that after creating the file instance using the directory and file name, file.exists () returns false , even if the file really exists in this place. I was browsing the SD card using the Android file browser and through Windows Explorer, and the file exists.

Is it right to check if the file exists, and if so, what am I missing for it to return 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? { ... } 
+6
java android file file-io
source share
3 answers

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

Java file documentation

public boolean createNewFile () throws an IOException. Atomically creates a new empty file, called this abstract empty, if and only if a file with this name does not yet exist. Checking for a file and creating a file if it does not exist is one operation that is atomic with respect to all other file system actions that can affect the file. Note. This method should not be used to lock files, because the received protocol cannot be reliably executed. Instead, use the FileLock tool.

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

+6
source share

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

First you need to write data.

+4
source share

I had the same problem, but with yarn on hadoop, where the spark task was trying to execute a command.

This is a file resolution issue. I fixed it with the code as shown below in scala. exists and notExists both return false, which means that jvm cannot determine if the file exists or not.

 import java.nio.file.Path import java.nio.file.Paths val path = Paths.get(fileLocation); println(":"+ Files.exists(path)+ ":" + Files.notExists(path)) 
0
source share

All Articles