算法练习(48): Queue的应用之文件列表(1.3.43)

本系列博客习题来自《算法(第四版)》,算是本人的读书笔记,如果有人在读这本书的,欢迎大家多多交流。为了方便讨论,本人新建了一个微信群(算法交流),想要加入的,请添加我的微信号:zhujinhui207407 谢谢。另外,本人的个人博客 http://www.kyson.cn 也在不停的更新中,欢迎一起讨论

算法(第4版)

知识点

  • 文件列表

题目

1.3.43 文件列表。文件夹就是一列文件和文件夹的列表。编写一个程序,从命令行接受一个文件夹名作为参数,打印出该文件夹下的所有文件并用递归的方式在所有子文件夹的名下(缩进)列出其下的所有文件。


1.3.43 Listing files. A folder is a list of files and folders. Write a program that takes the name of a folder as a command-line argument and prints out all of the files contained in that folder, with the contents of each folder recursively listed (indented) under that folder’s name. Hint : Use a queue, and see java.io.File.

分析

本人所有简书的算法文章详细分析已经移入小专栏:算法四习题详解,欢迎大家订阅

答案

public static void printFile(File file,int cengji){
    File[] tempList = file.listFiles();
    for (int i = 0; i < tempList.length; i++) {
        File fileItem = tempList[i];

        String str = "";
        for (int j = 0; j < cengji; j++) {
            str = str + " ";
        }
        System.out.println(str + fileItem.getName());

        if (fileItem.isDirectory()) {
            printFile(fileItem,cengji + 1);
        }
    }
}

public static void main(String[] args)
{
    String path = "/Users/kyson/Desktop/";
    File file = new File(path);
    printFile(file,0);
}

可惜,以上代码使用到了递归,但没有使用到队列。

广告

我的首款个人开发的APP壁纸宝贝上线了,欢迎大家下载。

壁纸宝贝

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容