File.exists() returns false when file exists

JavaFile Io

Java Problem Overview


I've encountered a bug I can't seem to find any logic behind. I have this File object, which is created like this:

File file = new File("utilities/data/someTextFile.txt");

I then do file.exists(), and it returns false (!?). If the file is not found, I'm logging f.getAbsolutePath() to a file. When I look at the path, it seems OK. I can copy-paste the complete path into the "Run"-window in Windows and the file opens fine.

The file exists at all times and is not deleted nor changed during the running of my application. It is located at the local machine.

This only seems to occur in certain situations. I can reproduce the fault at any time, but I'm sure the path of the file object is not changed by the actions I make to reproduce the fault.

What can cause file.exists() to return false? Does this have something to do with permissions or file locks, etc.?

Java Solutions


Solution 1 - Java

I am seeing the following situation on Windows 7:

file.exists() == false
file.getAbsoluteFile().exists() == true

The file in question is "var\log", the absolute path does refer to an existing file that is in a normal subdirectory (not a virtual store). This is seen from the IDE.

Solution 2 - Java

It seems like there is a difference on how the path is specified in Java.

For example, if the file path is specified as file:/C:/DEV/test.txt then

File f = new File(filename);
f.exists();

will return false. The path might work in the explorer or in the browser, but it is a URL and not absolute file path.

But on the other hand if the file path is specified as C:/DEV/test.txt then

File f = new File(filename);
f.exists();

will return true because the path is not a URL, but it is a absolute path.

With Spring Framework that is exactly what ResourceUtils.getFile(filename) does - where name can be either a URL or the absolute file path.

Solution 3 - Java

If the process does not have permissions to tell whether a file exists it will return false. It may be possible to open a file, but not tell by normal methods if it exists.

Solution 4 - Java

The above answers didn't help out in my case. As stated above, I had:

file.exists() => false
file.getAbsoluteFile().exists => true

The root cause for this was that the Windows 7 machine owner had modified the registry for CMD so that it would autorun a command to launch in a specific directory to work with Python. This modification crippled the Java 1.6 code which apparently uses CMD on Windows for certain file operations, such as exists(). Eliminating the autorun from the registry solved the issue.

Solution 5 - Java

When ["Hide extensions for known file types."] is checked windows open "t.txt.txt" when type "t.txt" in [explorer]/[run windows] but programmatically not.

Solution 6 - Java

Obviously there are a number of possible causes and the previous answers document them well, but here's how I solved this for in one particular case:

A student of mine had this problem and I nearly tore my hair out trying to figure it out. It turned out that the file didn't exist, even though it looked like it did. The problem was that Windows 7 was configured to "Hide file extensions for known file types." This means that if file appears to have the name "data.txt" its actual filename is "data.txt.txt".

Hope this helps others save themselves some hair.

Solution 7 - Java

If you don't want to deal with getAbsoluteFile() calls each time you have to call a method, you better create your file instance already with an absolute path. This should do the trick:

File file = new File("utilities/data/someTextFile.txt").getAbsoluteFile();

I suggest to surround it with a try-catch block, BTW.

Solution 8 - Java

The new File command just creates an instance of a file using the given path name. It doesn't actually create a file on the hard drive.

If you say

File file = new File ("path");
file.exists() 

This can return true only if there was an existing file with the same path. If you intended to check for the same file declared in the first line, you may need to use it this way.

File file = new File ("path");
file.createNewFile();
file.exists();

Now this will return true.

Solution 9 - Java

To generalize the issue the problem arises while converting URL/URI to local paths.

Example: URL url = file:/D:/code%20repo%20sample/sample.txt

// To remove url reference
String localPath = url.getPath();  
> /D:/code%20repo%20sample/sample.txt

// Decoding reserved characters in url from hexadecimal to character
URLDecoder.decode(localPath, StandardCharsets.UTF_8.toString()); 
> /D:/code repo sample/sample.txt

Hope this helps.

Solution 10 - Java

In my case

file save in

filepath = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/VRSI/Audio/"+encrypted_filename+".mp3";

It is stored in in

/storage/emulated/0/VRSI/Audio/82B0999F16251F0DFE849F380D6AAEEA.mp3

it when when I get the file path is

/storage/emulated/0/Android/data/com.numerotec.vrsi/files/VRSI/Audio/AF7DC6C0C0B3EF3529EC70DAEF2324E0.mp3

So I replace the the string "Android/data/com.numerotec.vrsi/files/" as empty

after that

if (file.getAbsoluteFile().exists())
{
    // write your code
} 

is working fine

Solution 11 - Java

If the situations where it fails involves running it as another user, and you're on Windows Vista/Windows 7, it could be caused by VirtualStore, the mechanism where Windows let an unprivileged user "write" places it normally cannot. The changes are however stored in "%USERPROFILE%\AppData\Local\VirtualStore" which are private to each user account.

Solution 12 - Java

Good responses everyone. I've found this seems to be a problem with Java accessing the root C: directory on Windows. Any other directory should be fine, but for some reason, specifically mentioning C:\ or C: or C:/ might give an error. I have resolved this very similar problem by trapping mention to new File("C:"); and replacing it with new File(System.getProperty("file.separator")); or you should be able to hard code "\" instead of saying "c:" as your file directory and it might work out. Not elegant, but got the job done for me on this project.

I hope it helps. Might not be the right solution, but at least it worked for me. I'm on JRE 1.6, Win 7. Cheers!

Respectfully,

@Carpenter1010

Solution 13 - Java

When nothing from above worked for me, I tried

filePath = filePath.trim();

This will clean your string from any unwanted charachter

Solution 14 - Java

FWIW, there is another place that this happens.

File("") is the name of the current directory. File("").exists() will usually return false. The File(("").getAbsoluteFile().exists() trick works and will return true (presuming the current directory exists...)

Solution 15 - Java

I lately came across this same issue. What l did was to uninstall Netbeans, deleted netbeans folder from C drive, program files, update, programData, virtually everywhere. Then reinstall. Is now working fine. Don't forget to backup up netbeans project folder before taken the actions above.

Hope it helps.

Solution 16 - Java

With some IDE(may be) and or with some OS(ex: window), by default they don't have write access on files. So if you try to do file.exists() it will show you false. in order to fix this, do like below

if your ref variable for File is f, example: File f = new File("path");

so in order to make it work , select f by mouse and then go to Search menu > Write access>Workspace. Hopefully it will work.

Solution 17 - Java

I think you should use backslash instead , like this:

File file = new File("C:\\User\\utilities\\data\\someTextFile.txt"); (two backslashes , not a typo )

Should solve the problem :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionatsjooView Question on Stackoverflow
Solution 1 - JavaRoman ZenkaView Answer on Stackoverflow
Solution 2 - JavaGarima BathlaView Answer on Stackoverflow
Solution 3 - JavaTom Hawtin - tacklineView Answer on Stackoverflow
Solution 4 - JavaKarl LewView Answer on Stackoverflow
Solution 5 - JavametooView Answer on Stackoverflow
Solution 6 - JavapetehernView Answer on Stackoverflow
Solution 7 - JavaFran MarzoaView Answer on Stackoverflow
Solution 8 - JavaR1234View Answer on Stackoverflow
Solution 9 - JavaArunView Answer on Stackoverflow
Solution 10 - JavaGanesan JView Answer on Stackoverflow
Solution 11 - JavaKjetil JoergensenView Answer on Stackoverflow
Solution 12 - JavaCode CarpenterView Answer on Stackoverflow
Solution 13 - JavaAsimView Answer on Stackoverflow
Solution 14 - JavaG. Blake MeikeView Answer on Stackoverflow
Solution 15 - JavaEvaboyView Answer on Stackoverflow
Solution 16 - JavaGautam AnandView Answer on Stackoverflow
Solution 17 - JavaHussein MaziadView Answer on Stackoverflow