1.3.43

question:

Listing files. A folder is a list of files and folder. 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.

answer:

//用队列递归输出文件夹及其内的文件

import edu.princeton.cs.algs4.*;
import java.io.File;

public class Listingfiles<Item>
{
    private class Node 
    {
        Item item;
        Node next;
    }
    
    private Node head;
    private Node tail;
    private int N;
    
    public int size()
    {
        return N;
    }
    
    public boolean isEmpty()
    {
        return N == 0;
    }
    
    public void enqueue(Item item)//入队
    {
        Node node = new Node();
        node.item = item;
        node.next = null;
        if(head == null)
        {
            N++;
            tail = head = node;
            return;
        }
        N++;
        tail.next = node;
        tail = node;
    }
    
    public Item dequeue()//出队
    {
        if(N == 0)
        {
            return null;
        }
        Item item = head.item;
        head = head.next;
        N--;
        return item;
    }
    
    public static void listingfiles(String path, Listingfiles<String> queue,int depth)
    {
        File f = new File(path);
        File[] list = f.listFiles();
        for(File temp:list)
        {
            String c = temp.getName();
            for(int i = 0; i < depth; i++)//便于区分文件层次
            {
                c = "\t" + c;
            }
            queue.enqueue(c);//入队
            if(temp.isDirectory())
            {
                listingfiles(temp.getAbsolutePath(), queue,depth + 1);//递归
            }
        }
        return;
    }
    
    public static void main(String[] args)
    {
        String path = "/home/weijianchao/test";//这是我用来测试的文件
        File f = new File(path);
        Listingfiles<String> queue = new Listingfiles<String>();
        queue.enqueue(f.getName());
        listingfiles(path,queue,1);
        while(!queue.isEmpty())
        {
            StdOut.println(queue.dequeue());
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/w-j-c/p/9090492.html