isDirectory() returns true for a file

筅森魡賤 提交于 2020-01-15 05:54:18

问题


In my java program I copy a file and delete the new file.

In my method removeFile() I check if it is a directory:

String fileName = "G:/1310628353186Examples.csv";
File f = new File(fileName);
if (f.isDirectory()) {
    System.out.println( "'" + fileName + "' is a directory" );
    String[] files = f.list();
    if (files != null && files.length > 0)
        throw new IllegalArgumentException("Delete: directory not empty: " + fileName);
}

Sometimes I get "'G:/1310628353186Examples.csv' is a directory", sometimes I don't.

When I debug the code and f.isDirectory() is true and I check what is in f.isDirectory, the debugger says that it's false.

I'm running Eclipse SDK 3.4.0 and JDK 1.6 on Windows 7 Professional.


回答1:


You check if f is a directory but you print fileName. So maybe you just check/print the wrong variable? Unless it's only a typo in your question.




回答2:


Try adding a check to see if the file exists, isDirectory() will also return false in case the file doesn't exist:

if (f.exists() && f.isDirectory()) {



回答3:


If the file is hidden, like the My Music link in Documents (a windows-generated shortcut file, it's not a real shortcut), then it will test as isdirectory but it won't function like a directory; you can't get a listing of the directory. A user generated shortcut will act like a file.

5/31/13: In a recent update the 'My Music' link in 'Documents' no longer tests as is_hidden. However, a dirlist taken of the file object for 'My Music' does return a NULL, which can be tested for.




回答4:


I get this same issue on OSX. I create a regular file, and the isDirectory() function returns true and isFile() returns false. (Can't find any evidence anywhere to suggest that this behaviour is expected from the API).

The way I solved it on OSX is to manually read the attributes from the file, but you can't use BasicFileAttributes either - it also for some reason returns true for isDirectory() and false for isRegularFile().

Works for OSX:

PosixFileAttributes attr = Files.readAttributes(f.toPath(), PosixFileAttributes.class);

System.out.println("File "+f.getName()+
                   ": isDirectory="+(attr.isDirectory() ? "true" : "false")+
                   ", isRegularFile="+(attr.isRegularFile() ? "true" : "false"));



回答5:


You have to sorround with try/catch block and then try it.




回答6:


It seemed to be a problem caused by Windows. Linux does not have this problem.



来源:https://stackoverflow.com/questions/6689941/isdirectory-returns-true-for-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!