考虑这个标准目录遍历代码:
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());
}
}
如果我在以下目录结构上执行它:c:\->Folder1 ->Folder2(=c:\Folder1的符号链接(symbolic link))
,在某个时刻f.listFiles ()
返回 null
。从文档中,listFiles
Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.
显然,路径表示一个目录。这可能意味着发生了 I/O 错误。但错误本身是什么?
最佳答案
有趣的是,如果您进行此更改
if(subs == null)
{
System.out.println("is now null");
File h = new File(f,"t");
h.createNewFile();
return; // returns null at some point
}
尝试在堆栈顶部创建文件,您会得到以下异常:
java.io.IOException: The name of the file cannot be resolved by the system
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
.....
此外,如果您只是添加检查它是否是目录
if(!f.isDirectory())
System.out.println("######## Not a Directory #####");
在堆栈顶部的位置,这将打印,因此 listFiles()
返回 null,因为它不是目录,因此不会抛出异常,这是由于操作系统和路太长了。
关于java - 当 Java 尝试递归地遍历带有循环符号链接(symbolic link)的目录结构时,会抛出什么样的 IO 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18452224/