关于Java程序中的递归例子,求帮助
阿神
阿神 2017-04-17 14:47:21
0
2
348

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);
        }
    }
}
阿神
阿神

闭关修行中......

reply all(2)
Ty80
list = f.list();

The list in this sentence may be null. Take a look at the documentation for the list function in File. It says:

  • @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.

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
if (list != null && list.length > 0)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template