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 prob开发者_JAVA技巧lem 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?
{
...
}
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
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.
I had the exact same issue but with yarn on hadoop where a spark job was trying to execute a command.
It was a file permission issue. I troubleshooted it by code like below which is in scala. exists and notExists both return false, which means the jvm is not able to tell 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))
精彩评论