Blog

It's a Wonderful Life

使用java罗列目录下的文件

2017-04-25 18:46 Posted in Learn with Java

直接上代码吧。

package com.leo.util;

import java.io.File;
import java.io.IOException;

public final class Lister
{

    private Lister()
    {
        throw new AssertionError();
    }
    
    public static void list(String folderString, int level) throws IOException
    {
        File folder = new File(folderString);
        
        if (! folder.isDirectory())
        {
            System.out.println("Given string is not a folder");
            return;
        }
        
        File[] fileList = folder.listFiles();
        
        for (File file : fileList)
        {
            if (file.isDirectory())
            {
                for (int i = 0; i < level; i++)
                {
                    System.out.print("\t");
                }
                System.out.println(file.getName());
                int subLevel;
                Lister.list(file.getAbsolutePath(), subLevel = level + 1);
            }
            else
            {
                for (int i = 0; i < level; i++)
                {
                    System.out.print("\t");
                }
                System.out.println(file.getName());
            }
        }
    }
}

另一个办法是使用java.nio.file的AIP

package com.leo.util;

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public final class Lister
{

    private Lister()
    {
        throw new AssertionError();
    }
    
    public static void list(String folder) throws IOException
    {
        Path folderPath = Paths.get(folder);
        Files.walkFileTree(folderPath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
            {
                System.out.println(file.getFileName().toString());
                return FileVisitResult.CONTINUE;
            }
        });
    }
    
}