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);
}
}
}
The list in this sentence may be null. Take a look at the documentation for the list function in File. It says:
When File is not a directory or an I/O error occurs, null will be returned.
You should have an I/O error here, so the next statement will report a null pointer exception.
PS: There may be a hidden folder
System Volume Information
under your D drive, and an error will be reported when accessing this folder.@lhcpig’s answer is already very good. Add:
in front of the for loop