当文件存在时,File.vis()返回 false

我遇到了一个我似乎找不到任何逻辑的错误。我有这个 File 对象,它是这样创建的:

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.

该文件始终存在,在应用程序运行期间不会删除或更改。它位于本地机器上。

这似乎只发生在某些情况下。我可以在任何时候重现错误,但是我确信 file 对象的路径不会因为我重现错误的操作而改变。

是什么导致 file.exists()返回 false? 这是否与权限或文件锁等有关?

112508 次浏览

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.

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.

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.

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.

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.

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.

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

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.

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.

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

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.

When nothing from above worked for me, I tried

filePath = filePath.trim();

This will clean your string from any unwanted charachter

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.

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.

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.

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

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

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