简体   繁体   English

如何列出目录及其所有子目录中的所有文件

[英]How to list all files within a directory and all its sub-directories

I've made a program that lists all file names in a desired directory of your extension choice. 我制作了一个程序,该程序列出了扩展名所需目录中的所有文件名。 Now I want to and I don't know how to change it to list all files within sub-directories too. 现在,我想要并且不知道如何更改它,以便也列出子目录中的所有文件。 Do you have any ideas? 你有什么想法? Here's my code. 这是我的代码。 Thanks! 谢谢!

import java.util.*;
import java.io.*;

public class Program {

    public static void main(String str[]){
        try{
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("1.Enter directory name:");
            String adress = br.readLine();
            System.out.println("2.Enter file extension:");
            String exten = br.readLine();

            File directory = new File(adress);

            File[] f = directory.listFiles();     

            List<String> files = new ArrayList<String>();
            List<String> valid = new ArrayList<String>();
            List<String> names = new ArrayList<String>();

            for(int i=0; i < f.length; i++){
                if(f[i].isFile()){
                    files.add(f[i].getName());
                }
            }

            for(int i=0; i < files.size(); i++){
                if (files.get(i).endsWith(exten)){
                    valid.add(files.get(i));
                }
            }

            for(int i=0; i < valid.size(); i++){
                int pos = valid.get(i).lastIndexOf(".");
                    names.add(valid.get(i).substring(0, pos));
                    System.out.println(names.get(i));
            }
       }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}

If you can use Java 7 or 8 you could use the FileVisitor , but in Java 7 it means writing more then one line of code. 如果可以使用Java 7或8,则可以使用FileVisitor ,但是在Java 7中,这意味着要编写多行代码。 If not and you want to keep it simple, Apache Commons FileUtils may be your friend. 如果不是,并且您想保持简单,则Apache Commons FileUtils可能是您的朋友。

Collection<File> files = FileUtils.listFiles(path, new String[]{"xlxs"}, true);

I made this awhile back to find all of *.xls or *.xlsx in a directory. 我花了一会儿时间在目录中找到所有* .xls或* .xlsx。

Hope this will help you with your question. 希望这对您的问题有所帮助。

public static List<String> fileSearch(String d){
        List<String> filesFound = new ArrayList<String>();
        File dir = new File(d);
        try{
        for(File file: dir.listFiles()){
            if(file.isFile() && (file.getName().toLowerCase().endsWith(".xlsx") || file.getName().toLowerCase().endsWith(".xls"))){

                long filesize = file.length();
                long fileSize = filesize / 1024;

                filesFound.add(d + "\\" + file.getName());
                System.out.println("Added: " + d + "\\" + file.getName()  + "     " + fileSize + " KB" );
            }else if(file.isDirectory() && !file.isHidden()){
                System.out.println("Found Directory: " + file.getName());
                filesFound.addAll(fileSearch(d + "\\" + file.getName()));
            }else if(isRoot(file)){
                        //DO NOTHING
            }
        }

        }catch(NullPointerException ex){
            ex.printStackTrace();
        }finally{
            return filesFound;
        }
    }

private static boolean isRoot(File file){
        File[] roots = File.listRoots();

        for (File root : roots) {
            if (file.equals(root)) {
            return true;
            }
        }

        return false;
    }

What this does, it will search every file for a match and if it matches then it will add it to the array "filesFound" from there you can get all the paths of matched files. 这样,它将在每个文件中搜索一个匹配项,如果匹配,则将其添加到数组“ filesFound”中,您可以获取所有匹配文件的路径。 BUT for you, you would take out the .xlsx and .xls part and add in your ext. 但对于您来说,您将取出.xlsx和.xls部分并添加您的ext。

fileSearch(String d, String ext)

and change the if then to: 并将if then更改为:

if(file.isFile() && file.getName().toLowerCase().endsWith(ext))

ALSO i have it outputting when ever it finds a match with the file size next to it. 我也有输出,无论何时找到与它旁边的文件大小匹配的文件。 The file size is just a visual aid and does not get included in the array. 文件大小只是视觉上的帮助,并不包含在数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 列出目录中所有文件(包括子目录)的最有效方法是什么? - What is the most efficient way to list all of the files in a directory (including sub-directories)? 通过目录及其子目录中的所有文件搜索存储在数组列表中的值 - searching for values stored in an arraylist through all the files within a directory and its sub directories 我是否必须手动列出其中的所有子目录 <resources> 在Java POM中 - Do I have to manually list all sub-directories within <resources> in Java POM 读取目录中的所有文件,包括其子目录 - Reading all files in a directory including its sub directories 如何在目录/文件夹中查找子目录? - How to find sub-directories in a directory/folder? Eclipse在没有文件的Antlr生成的代码目录上显示警告,但在其子目录上不显示警告 - Eclipse shows warning on Antlr generated code directory with no files, but not on its sub-directories 如何从目录和子目录复制具有某些扩展名的所有文件? - How to copy all files with certain extensions from a directory and sub directories? 列出Azure中(子)目录中的所有文件 - List all files in (sub)directories in Azure 在 IntelliJ IDEA 中将所有子目录 JAR 添加到依赖项中 - Add all sub-directories JARs into dependencies in IntelliJ IDEA 如何复制目录及其子目录,文件和zip文件 - How to copy a directory with its sub directories , files and zip files
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM