101

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.?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
atsjoo
  • 2,412
  • 4
  • 20
  • 22
  • So, is it possible to read from the file even if exists() returns false? – Harry Lime May 28 '09 at 09:24
  • yes, I can read from the file even if exists() returns false. – atsjoo May 28 '09 at 09:37
  • Have you tried different JVMs? Different machines? Different Operating Systems? – Harry Lime May 28 '09 at 09:47
  • 1
    What exactly is needed to reproduce the fault? – user85421 May 28 '09 at 11:05
  • 1
    This is inside an application which calls functions written in matlab and compiled into the java application. It seems like matlab functions which changes the "current directory" is causing the problem to appear. I am using the absolute path when creating the file object, so this shouldn't be a problem - however it seems to be. I have of course verified the absolute path of the file object, and it is correct (the same as it was before the matlab function changed the current directory). – atsjoo May 28 '09 at 11:33
  • 7
    Are you by any chance working against a remote directory (e.g. an NFS mount)? – Tomer Gabel Aug 03 '09 at 03:10
  • This is easily reproducible in Netbeans by creating a unit test that creates a file (e.g. writes a zip file) and then checks if it exists. Would be nice if someone found definitive reason. – Bloodboiler May 18 '11 at 12:29
  • try adding a / at the start so javac wont assume it's according to the Classpath. This happens a lot when you're working in an IDE, like Netbeans and you put this on the src directory... does it help? – fixmycode May 28 '09 at 10:22

18 Answers18

47

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.

The operations running on file are resolved against the current directory, while getAbsolutePath resolves against user.dir. If these two paths do not match, you get conflicting results.

See https://bugs.java.com/bugdatabase/view_bug?bug_id=4483097

Roman Zenka
  • 3,514
  • 3
  • 31
  • 36
  • 18
    Apparently, the operations running on file are resolved against the current directory, while getAbsolutePath resolves against user.dir. If these two paths do not match, you get conflicting results. Devilish! – Roman Zenka Jul 08 '10 at 14:36
  • 3
    I have the exact same problem I tried to use both methods to check if file exists, and still I get false on Windows 7 only! Any idea? – Dejell Sep 20 '10 at 09:26
  • @Odelya: What IDE are you using? What is your -Duser.dir set to? My problem was caused by setting -Duser.dir to a different directory than the current working one. – Roman Zenka Sep 22 '10 at 14:26
  • 1
    For anyone who is working on a Dynamic Web Project, using file.exists() will throw an exception, use file.getAbsoluteFile().exists() to check for files in the WEB-INF directory (general tip, not Windows 7 specific). – P-S Apr 21 '16 at 09:22
  • Consider creating a separate QA for this answer and comments – Bato-Bair Tsyrenov Nov 26 '18 at 12:58
  • 2
    @RomanZenka The link is broken, the working one is https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4483097 – kutschkem Aug 01 '22 at 15:37
  • 1
    Updated link: [https://bugs.java.com/bugdatabase/view_bug?bug_id=4483097](https://bugs.java.com/bugdatabase/view_bug?bug_id=4483097) – wknauf Apr 23 '23 at 09:40
17

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Garima Bathla
  • 179
  • 1
  • 2
  • 6
    I wouldn't expect `file:/C:/DEV/test.txt` to work as a pathname. It's a URL not a pathname. While some people make this mistake, there is no evidence that the OP has ... – Stephen C Oct 27 '14 at 22:43
15

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.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
  • 21
    Interesting. Can you expand on this? Which specific permissions do you have in mind? – Clément Nov 21 '11 at 23:44
  • Here can be java.nio.file.AccessDeniedException blocking ability to reach out file/dir existence. For instance, if you keep dir opened in FAR or other file explorer, then delete dir with all nested files and check existence of this dir, then you can get AccessDeniedException (extends IOException) for temporary file kept for you. In this case Files.exists returns false for IOException. – Alfira Apr 10 '17 at 14:27
12

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.

mabarroso
  • 659
  • 2
  • 11
  • 23
Karl Lew
  • 121
  • 1
  • 2
  • 1
    3.5 years later, and I ran into the same issue. I had an autorun script set up to configure environment variables each time I launched cmd.com. It didn't even change the current directory -- just some doskey macros and some environment variables. I removed the autorun, and just manually ran the commands in the file, and suddenly File.exists() works correctly. – Homr Zodyssey Mar 01 '16 at 19:18
  • 2
    OMG, it really works (both of them), I was just dumbly checking for the wrong file and came across this question to find out why none of them work for me :) BTW, it seems the `()` are missing in the second line after `exists` ;) – RAM237 Jul 05 '17 at 13:55
5

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.

metoo
  • 51
  • 1
  • 1
  • 2
    I had this issue, and the problem was that I created a txt file, which was called 'testFile.txt', in C:\test. I referred to this file using the path C:\test\testFile.txt, which didn't work. It was because the file had actually been saved as testFile.txt.txt, hence the up vote on the above solution (Old question, but no accepted answer!) – Theblacknight Feb 22 '12 at 08:51
  • God Windows sucks so much. – aafc Jan 31 '14 at 16:54
3

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.

petehern
  • 803
  • 1
  • 8
  • 11
  • I don't think this was the issue in my case. As mentioned in my question: "I can copy-paste the complete path into the "Run"-window in Windows and the file opens fine.", which means the file actually does exist. – atsjoo May 08 '15 at 09:58
3

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.

Fran Marzoa
  • 4,293
  • 1
  • 37
  • 53
2

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
R1234
  • 484
  • 9
  • 20
  • small explanation: every call to constructor by use of new keyword creates an Object - same as in this case an Object described by Class which name is File ! so not a instance of File != descriptors :) – ceph3us May 23 '16 at 20:30
2

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.

Arun
  • 785
  • 8
  • 13
1

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

Syscall
  • 19,327
  • 10
  • 37
  • 52
Ganesan J
  • 539
  • 7
  • 12
0

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

Bishan
  • 15,211
  • 52
  • 164
  • 258
0

When nothing from above worked for me, I tried

filePath = filePath.trim();

This will clean your string from any unwanted charachter

Asim
  • 161
  • 1
  • 12
0

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...)

G. Blake Meike
  • 6,615
  • 3
  • 24
  • 40
0

My suggestion is to attempt to read the file.

By doing so, i was able to get this error, that showed me that some weird characters had been prepended to my path.

java.nio.file.NoSuchFileException: ‪/home/rasp2/MyProjects/mapping.txt

In my IDE this was the path i was seeing:

Path path = Paths.get("/home/rasp2/MyProjects/mapping.txt");

So... i really don't know how, but these characters ‪ got into the way.

By deleting the path in the IDE and recreating it, i was able to get Files.exists(path) == true

BabaNew
  • 884
  • 1
  • 13
  • 27
0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kjetil Joergensen
  • 1,595
  • 11
  • 10
-1

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.

Evaboy
  • 1
-2

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.

-3

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 :)

  • 4
    I think the issue is more related to absolute path vs relative path. The slash are valid in Java even for Windows paths. – рüффп Sep 21 '16 at 18:32