java:在目录和子目录中根据文件名搜索文件

发布于 2024-11-14 05:09:27 字数 634 浏览 2 评论 0原文

我需要根据目录树中的名称查找文件。然后显示该文件的路径。我发现了类似的东西,但它根据扩展名进行搜索。谁能帮助我如何根据我的需要重新编写这段代码...谢谢

public class filesFinder {
public static void main(String[] args) {
    File root = new File("c:\\test");

    try {
        String[] extensions = {"txt"};
        boolean recursive = true;


        Collection files = FileUtils.listFiles(root, extensions, recursive);

        for (Iterator iterator = files.iterator(); iterator.hasNext();) {
            File file = (File) iterator.next();
            System.out.println(file.getAbsolutePath());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

I need a to find file according to its name in directory tree. And then show a path to this file. I found something like this, but it search according extension. Could anybody help me how can I rework this code to my needs...thanks

public class filesFinder {
public static void main(String[] args) {
    File root = new File("c:\\test");

    try {
        String[] extensions = {"txt"};
        boolean recursive = true;


        Collection files = FileUtils.listFiles(root, extensions, recursive);

        for (Iterator iterator = files.iterator(); iterator.hasNext();) {
            File file = (File) iterator.next();
            System.out.println(file.getAbsolutePath());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

断舍离 2024-11-21 05:09:28
public class Test {
    public static void main(String[] args) {
        File root = new File("c:\\test");
        String fileName = "a.txt";
        try {
            boolean recursive = true;

            Collection files = FileUtils.listFiles(root, null, recursive);

            for (Iterator iterator = files.iterator(); iterator.hasNext();) {
                File file = (File) iterator.next();
                if (file.getName().equals(fileName))
                    System.out.println(file.getAbsolutePath());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
public class Test {
    public static void main(String[] args) {
        File root = new File("c:\\test");
        String fileName = "a.txt";
        try {
            boolean recursive = true;

            Collection files = FileUtils.listFiles(root, null, recursive);

            for (Iterator iterator = files.iterator(); iterator.hasNext();) {
                File file = (File) iterator.next();
                if (file.getName().equals(fileName))
                    System.out.println(file.getAbsolutePath());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
淡笑忘祈一世凡恋 2024-11-21 05:09:28

Java 中的递归目录搜索非常简单。 java.io.File 类有一个 listFiles() 方法,该方法给出目录的所有 File 子目录;您还可以在 File 上调用一个 isDirectory() 方法来确定是否应该递归搜索特定子项。

Recursive directory search in Java is pretty darn easy. The java.io.File class has a listFiles() method that gives all the File children of a directory; there's also an isDirectory() method you call on a File to determine whether you should recursively search through a particular child.

心碎的声音 2024-11-21 05:09:28

您可以像这样使用 FileFilter 。

public class MyFileNameFilter implements FilenameFilter {

@Override
public boolean accept(File arg0, String arg1) {
    // TODO Auto-generated method stub
    boolean result =false;
    if(arg1.startsWith("KB24"))
        result = true;
    return result;
}

像这样调用它

File f = new File("C:\\WINDOWS");
    String []  files  = null;
    if(f.isDirectory()) {  
        
        files = f.list(new MyFileNameFilter());
    }
    
    for(String s: files) {
        
        System.out.print(s);
        System.out.print("\t");
    }

Java 8 Lamda 使这更容易,而不是使用 FileNameFilter,传递 lambda 表达式

   File[] filteredFiles =  f.listFiles((file, name) ->name.endsWith(extn));
   

You can use FileFilter Like this.

public class MyFileNameFilter implements FilenameFilter {

@Override
public boolean accept(File arg0, String arg1) {
    // TODO Auto-generated method stub
    boolean result =false;
    if(arg1.startsWith("KB24"))
        result = true;
    return result;
}

}

And call it like this

File f = new File("C:\\WINDOWS");
    String []  files  = null;
    if(f.isDirectory()) {  
        
        files = f.list(new MyFileNameFilter());
    }
    
    for(String s: files) {
        
        System.out.print(s);
        System.out.print("\t");
    }

Java 8 Lamda make this easier instead of using FileNameFilter, pass lambda expression

   File[] filteredFiles =  f.listFiles((file, name) ->name.endsWith(extn));
   
何处潇湘 2024-11-21 05:09:28

我真的不知道 FileUtils 是做什么的,但是将扩展名中的“txt”更改为“yourfile.whatever”怎么样?

I don't really know what FileUtils does, but how about changing "txt" in extenstions to "yourfile.whatever"?

梦晓ヶ微光ヅ倾城 2024-11-21 05:09:28
public static File find(String path, String fName) {
    File f = new File(path);
    if (fName.equalsIgnoreCase(f.getName())) return f;
    if (f.isDirectory()) {
        for (String aChild : f.list()) {
            File ff = find(path + File.separator + aChild, fName);
            if (ff != null) return ff;
        }
    }
    return null;
}
public static File find(String path, String fName) {
    File f = new File(path);
    if (fName.equalsIgnoreCase(f.getName())) return f;
    if (f.isDirectory()) {
        for (String aChild : f.list()) {
            File ff = find(path + File.separator + aChild, fName);
            if (ff != null) return ff;
        }
    }
    return null;
}
眼角的笑意。 2024-11-21 05:09:28

在目录和嵌套子目录中查找文件:

import java.io.File;
import java.util.Objects;

public class Solution_LocateUniverseFormula {
    public static void main(String[] args) {
        System.out.println(locateUniverseFormula());
    }

    public static String locateUniverseFormula() {
        File root = new File("C:/tmp/documents/");
        String fileName = "universe-formula";

        File[] files = root.listFiles();

        for (File childFile : files) {
            String filePath = find(childFile, fileName);
            if (!Objects.isNull(filePath)) return filePath;
        }

        return null;
    }

    public static String find(File file, String fileName) {
        if (file.getName().startsWith(fileName)) return file.getAbsolutePath();
        if (file.isDirectory()) {
            for (File childFile : file.listFiles()) {
                String filePath = find(childFile, fileName);
                if (!Objects.isNull(childFile)) return filePath;
            }
        }
        return null;
    }
}

Find File in a Directory and Nested Sub-Directories :

import java.io.File;
import java.util.Objects;

public class Solution_LocateUniverseFormula {
    public static void main(String[] args) {
        System.out.println(locateUniverseFormula());
    }

    public static String locateUniverseFormula() {
        File root = new File("C:/tmp/documents/");
        String fileName = "universe-formula";

        File[] files = root.listFiles();

        for (File childFile : files) {
            String filePath = find(childFile, fileName);
            if (!Objects.isNull(filePath)) return filePath;
        }

        return null;
    }

    public static String find(File file, String fileName) {
        if (file.getName().startsWith(fileName)) return file.getAbsolutePath();
        if (file.isDirectory()) {
            for (File childFile : file.listFiles()) {
                String filePath = find(childFile, fileName);
                if (!Objects.isNull(childFile)) return filePath;
            }
        }
        return null;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文