Java:解析目录和子目录以检查特定类型的文件

时间:2016-06-26 16:54:02

标签: java

描述:我正在尝试解析我的主目录以查找“.jpg”类型的所有文件,我的代码能够返回所需的所有文件。示例“C:\ Ravi \ Sources”,在此目录中我有.xml,.jpg,.gif的混合文件,现在我也在这个目录中有子文件夹,但我不知道 如何修改我的代码以检查子目录。

此处需要专业知识帮助:

代码段:

enter code here




import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import java.io.PrintStream;


public class Subdirectory {

    static File f = new File("C:\\Users\\kasharma\\Desktop\\Travelocity R8.3_8.3.0.apk\\res");// File f will represent the folder....

static String[] extensions = new String[]{"png", "jpg", "gif" };  // Declaring array of supported filters...



// Applying filter to identify images based on their extensions...

static FilenameFilter Image_Filter = new FilenameFilter() {
    public boolean accept(File f, String name)
    {
        for(String ext: extensions){
            if(name.endsWith("."+ ext)){
                return(true);
            }
        }
        return(false);
    }
    };

    public static void goThroughDirectories(String path)
    {

        }

    public static void main(String[] args) {

          String path = "C:\\Users\\kasharma\\Desktop\\Travelocity R8.3_8.3.0.apk\\res";


            for (File file : f.listFiles(Image_Filter)) 
                {
                if (f.isDirectory()) goThroughDirectories(path+f.getName());

                BufferedImage img = null;

                try {
                    img = ImageIO.read(file); 
                    System.out.println("image "+ file.getName());
                } catch (IOException e) {
                    // handle errors here
                }

        }
        }
    }

2 个答案:

答案 0 :(得分:3)

查看java.nio.files,尤其是walkFileTree(...)find(...)方法。 Java 8包含内置功能。<​​/ p>

使用walkFileTree

public static void main(String[] args) throws Exception 
{
    Path p = Paths.get("D:/");
    Files.walkFileTree(p, 
            new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
                {
                    System.out.println(file.toFile().getName());
                    return FileVisitResult.CONTINUE;
                }
            }
        );
}

这是一个更好的解决方案,使用find同时返回一个延迟填充的流和.jpg的过滤器:

public static void main(String[] args) throws Exception
{
    Path p = Paths.get("D:/");
    Files
        .find(
            p, 
            Integer.MAX_VALUE, 
            (path,attr) -> path.toString().endsWith(".jpg"))
        .forEach(path -> System.out.println(path.toFile().getName()));
}

答案 1 :(得分:2)

这会给你一个想法。这是伪代码。

void goThroughDirectories(String path)
{
    for(File f : fileList)
    {
        if(f.isDirectory()) goThroughDirectories(path+f.getName());
        else {
                //do something
            }
    }
}