如何在java中打印所有目录和文件以及所有子目录和文件

我写了下面的代码我想改进我的代码中的所有子树,仅用于 2 层我想将我的代码更改为所有层的迭代代码。


    for(int p=0;p<f3.length;p++){


            if(f3[p].isDirectory()){

                System.out.println(f3[p]+"*****DIRECTORY*****");

                File[] fsub=f3[p].listFiles();

                for(int i=0;i<fsub.length;i++){

                    if(fsub[i].isDirectory()){

                    System.out.println(fsub[i]+"  DIRECTOY");}

                    else System.out.println(fsub[i]+"  FILE");

                }


                    }

            else System.out.println(f3[p]+"--FILE");

    }


郎朗坤
浏览 272回答 3
3回答

潇湘沐

试试这个:public class Test {public static void main(String[] args) throws IOException {&nbsp; &nbsp; File[] paths = File.listRoots();&nbsp; &nbsp; for (int i = 0; i < paths.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; showfiles(paths[i]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;}public static void showfiles(File dir) {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; File[] files = dir.listFiles();&nbsp; &nbsp; &nbsp; &nbsp; for (File file : files) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (file.isDirectory()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Directory:" + file.getCanonicalPath());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; showfiles(file);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("File:" + file.getCanonicalPath());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; }}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java