关于Java程序中的递归例子,求帮助
阿神
阿神 2017-04-17 14:47:21
[Java讨论组]

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

闭关修行中......

全部回复(2)
PHP中文网
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)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号