开发者

isDirectory() returns true for a file

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: dir开发者_运维知识库ectory 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.


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.


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()) {


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.


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"));


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜