开发者社区 问答 正文

关于Java程序中的递归

以D盘为目标路径,打印了几行就提示空指向异常其他盘几乎就直接提示空指向异常了

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

展开
收起
蛮大人123 2016-02-22 13:56:35 1837 分享 版权
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    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,访问这个文件夹时会报错。

    2019-07-17 18:46:37
    赞同 展开评论
问答分类:
问答标签:
问答地址: