scoobym 2015-10-17 16:03 采纳率: 0%
浏览 1922

java实现类似linux的tree命令,求解答

package javaiotest;

import java.io.*;
import java.util.Scanner;

public class FileExplore {

private File file = null;
public int fileNum = 0;
public int dirNum = 0;
public FileExplore(){
    System.out.println("请输入要遍历的目录:");
    Scanner console = new Scanner(System.in);
    String filepath = console.next();
    file = new File(filepath);
    console.close();
}

public  String getDepth(File file){
    File temp = file;
    String depth = new String();
    while(temp!=this.file){
        depth+="   ";
        temp = temp.getParentFile();
    }
    return depth;
}


public void treeOfFile(File file){

    if(!file.exists())
        System.out.println("file is null!");
    if(file.isFile()){
        System.out.println(this.getDepth(file)+"|--"+file.getName());
        fileNum++;
        }
    if(file.isDirectory()&&file.list().length==0){
        System.out.println(this.getDepth(file)+"|--" +file.getName());
        dirNum++;
    }
    if(file.isDirectory()&&file.list().length>0)
    {
        dirNum++;
        System.out.println(this.getDepth(file)+"|--"+file.getName());
        File[] filelist = file.listFiles();
        for(int i=0;i<filelist.length;i++){
            treeOfFile(filelist[i]);
        }

    }
}

public static void main(String[] args) {

    FileExplore demo = new FileExplore();
    demo.treeOfFile(demo.file);
    System.out.println("文件夹数量:"+ demo.dirNum);
    System.out.println("文件数量:"+ demo.fileNum);
}

}
结果抛出空指针异常,是在那个getDepth出错的,可是看不出来哪里错了

  • 写回答

2条回答

  • threenewbee 2015-10-17 16:19
    关注

    while(temp!=this.file)
    不能这么写应该是
    while(temp.getFileName().equals(this.file.getFileName()))

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器