Discuss / Java / 作业

作业

Topic source

よろしく

#1 Created at ... [Delete] [Delete and Lock User]
//用递归实现遍历文件夹所有子目录并展现层次结构
import java.io.File;
import java.io.IOException;
public class Main {
    public static void main(String[] args) throws IOException {
        getPath getpath = new getPath("..");
        getpath.printFile();
    }
}
class getPath{
    private File fs;
    getPath(){
        this.fs = new File(".");
    }
    getPath(String path){
        this.fs = new File(path);
    }
    void printFile(){
        System.out.println("================");
        pr(fs,0);
    }
    private void pr(File arg,int a){
        File[] fs1 = arg.listFiles();
        if(fs1 != null){
            for (File n: fs1){                
                if(n.isDirectory()){
                    System.out.println(new String(new char[a]).replace('\0', ' ') + n.getName()+'/');
                    a++;
                    pr(n,a);
                }else{
                    System.out.println(new String(new char[a]).replace('\0', ' ') + n.getName());
                }                
            }
        }
    }
}

在此内容下修改了一下最后的方法(输出的文件和目录层次更清晰):

    private void pr(File arg,int depth){
        File[] fs1 = arg.listFiles();
        if(fs1 != null){
            for (File n: fs1){
                if(n.isDirectory()){
                    int Tempdepth=depth;
//                    System.out.println(new String(new char[a]).replace('\0', ' ') + n.getName()+'/');                    System.out.println(" ".repeat(Tempdepth) + n.getName()+'/');
                    Tempdepth++;
                    pr(n,Tempdepth);
                }else{
//                    System.out.println(new String(new char[a]).replace('\0', ' ') + n.getName());                    System.out.println(" ".repeat(depth) + n.getName()+'/');                }
            }
        }
    }

在此内容的基础下修改了一下最后的方法(输出的文件和目录层次更清晰):

    private void pr(File arg,int depth){
        File[] fs1 = arg.listFiles();
        if(fs1 != null){
            for (File n: fs1){
                if(n.isDirectory()){
                    int Tempdepth=depth;//用一个变量记录临时的目录层次,当一个目录下有多个文件或目录时,原本的目录层次就没有打乱
                    //System.out.println(new String(new char[a]).replace('\0', ' ') + n.getName()+'/');                    
                    System.out.println(" ".repeat(Tempdepth) + n.getName()+'/');
                    Tempdepth++;
                    pr(n,Tempdepth);
                }else{
                    //System.out.println(new String(new char[a]).replace('\0', ' ') + n.getName());                    
                    System.out.println(" ".repeat(depth) + n.getName()+'/');                }
            }
        }
    }

  • 1

Reply