Java自学者,最近看到IO,做到一个递归列出文件列表的例子
自己写的不对,仿照例子一样写的,结果也跑不起来
以D盘为目标路径,打印了几行就提示空指向异常
其他盘几乎就直接提示空指向异常了
求帮助,谢谢!
import java.io.*;
public class JavaTest26_04{
public static void main(String args[]){
JavaTest26_04 j = new JavaTest26_04();
j.loop("d:\\");
}
public void loop(String lj){
String list[] = null;
File f = new File(lj);
if(f.isDirectory()){
list = f.list();
for(int i=0;i<list.length;i++){
loop(lj + "\\" + list[i]);
}
}
else{
System.out.println(lj);
}
}
}
list = f.list();
这一句中list可能为null。看一下File里面的list函数的文档,上面有写:
@return An array of strings naming the files and directories in the
directory denoted by this abstract pathname. The array will be
empty if the directory is empty. Returns {@code null} if
this abstract pathname does not denote a directory, or if an
I/O error occurs.
当File不是目录或者发生I/O错误的时候,会返回null。
你这里应该是发生I/O错误了,所以下一个语句会报空指针异常。
PS:可能是你的D盘下有一个隐藏的文件夹System Volume Information
,访问这个文件夹时会报错。
@lhcpig的解答已经很好了。在for循环前面添加:
if (list != null && list.length > 0)