0

Consider this standard directory traversal code:

static void walk(File f) throws IOException{
    System.out.println(f.getPath());

    if(f.isFile()) return;  // leaf

    File[] subs = f.listFiles(); // If it aint a file, it's a directory. Right? 

    if(subs == null) return; // returns null at some point

    for(File subDir : subs){
        walk(subDir.getAbsoluteFile()); 
    }
}

If I execute it on the following directory structure: c:\ -> Folder1 -> Folder2 (=a symbolic link to c:\Folder1), at some point f.listFiles() returns null. From the documentation, listFiles

Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.

Clearly, the path denotes a directory. This probably means an I/O error occurs. But what is the error itself?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Vitaliy
  • 8,044
  • 7
  • 38
  • 66
  • 4
    That's probably a path-too-long error. – SLaks Aug 26 '13 at 20:14
  • If folder2 links to folder1 don't you get a directory loop? – Cruncher Aug 26 '13 at 20:15
  • Your question is obviously operating system specific (but you seems to care only about Windows). On Linux and Posix systems, you might get the `ELOOP` error code given by some syscall, see [errno(3)](http://man7.org/linux/man-pages/man3/errno.3.html) – Basile Starynkevitch Aug 26 '13 at 20:17
  • @Cruncher, yes, as I stated in the question itself. – Vitaliy Aug 26 '13 at 20:19
  • You might want to take a look at the native source code for Win32FileSystem [here](http://hg.openjdk.java.net/jdk6/jdk6-gate/jdk/file/2a0c219cf228/src/windows/native/java/io/Win32FileSystem_md.c). It's JDK6, but just for kicks. the `Java_java_io_Win32FileSystem_list` is what you are looking for, but again the errors must be hidden with method calls. Go down the rabbit whole. I don't know `c`. – Sotirios Delimanolis Aug 26 '13 at 20:34

1 Answers1

1

Interestingly, if you make this change

if(subs == null) 
{
    System.out.println("is now null");
    File h = new File(f,"t");
    h.createNewFile();
    return; // returns null at some point
}

to try and create a file at the top of the stack, you get this exception:

java.io.IOException: The name of the file cannot be resolved by the system
       at java.io.WinNTFileSystem.createFileExclusively(Native Method)
       .....

Also if you just add a check for if it is a directory

if(!f.isDirectory())
    System.out.println("######## Not a Directory  #####");

at the point at the top of the stack this will print, so therefore listFiles() returns null because it is not a directory, so no exception thrown, which would be due to OS and the path being to long.

Java Devil
  • 10,629
  • 7
  • 33
  • 48