Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Java查找文件夹中的文件_Java_File_Search_For Loop_Directory - Fatal编程技术网

使用Java查找文件夹中的文件

使用Java查找文件夹中的文件,java,file,search,for-loop,directory,Java,File,Search,For Loop,Directory,如果搜索文件夹时说C:\example 然后,我需要检查每个文件,看看它是否匹配一些开始字符,以便文件是否开始 temp****.txt tempONE.txt tempTWO.txt 因此,如果文件以temp开头,扩展名为.txt,我想将该文件名放入file file=new file(“C:/example/temp***.txt”);中,这样我就可以读入该文件,然后循环需要移动到下一个文件,以检查它是否符合上述要求。您想要的是 这将为您提供目录中与特定筛选器匹配的文件列表 代码将类似于:

如果搜索文件夹时说
C:\example

然后,我需要检查每个文件,看看它是否匹配一些开始字符,以便文件是否开始

temp****.txt
tempONE.txt
tempTWO.txt
因此,如果文件以temp开头,扩展名为.txt,我想将该文件名放入
file file=new file(“C:/example/temp***.txt”);
中,这样我就可以读入该文件,然后循环需要移动到下一个文件,以检查它是否符合上述要求。

您想要的是

这将为您提供目录中与特定筛选器匹配的文件列表

代码将类似于:

// your directory
File f = new File("C:\\example");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return name.startsWith("temp") && name.endsWith("txt");
    }
});

查看
java.io.File.list()
FilenameFilter

您可以使用,如下所示:

File dir = new File(directory);

File[] matches = dir.listFiles(new FilenameFilter()
{
  public boolean accept(File dir, String name)
  {
     return name.startsWith("temp") && name.endsWith(".txt");
  }
});

以Apache Commons IO为例,它有一个名为的类,该类有一个在您的情况下可能非常有用的方法。

Appache Commons IO

FilenameUtils.wildcardMatch


请参阅Apache javadoc。它将通配符与文件名匹配。因此,您可以使用此方法进行比较。

用于列出给定目录中的Json文件

import java.io.File;
    import java.io.FilenameFilter;

    public class ListOutFilesInDir {
        public static void main(String[] args) throws Exception {

            File[] fileList = getFileList("directory path");

            for(File file : fileList) {
                System.out.println(file.getName());
            }
        }

        private static File[] getFileList(String dirPath) {
            File dir = new File(dirPath);   

            File[] fileList = dir.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.endsWith(".json");
                }
            });
            return fileList;
        }
    }

正如@Clarke所说,您可以使用
java.io.FilenameFilter
按特定条件过滤文件

作为补充,我想展示如何使用
java.io.FilenameFilter
在当前目录及其子目录中搜索文件

import java.io.File;
    import java.io.FilenameFilter;

    public class ListOutFilesInDir {
        public static void main(String[] args) throws Exception {

            File[] fileList = getFileList("directory path");

            for(File file : fileList) {
                System.out.println(file.getName());
            }
        }

        private static File[] getFileList(String dirPath) {
            File dir = new File(dirPath);   

            File[] fileList = dir.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.endsWith(".json");
                }
            });
            return fileList;
        }
    }
常用的getTargetFile和printFiles方法用于搜索和打印文件

public class SearchFiles {

    //It's used in dfs
    private Map<String, Boolean> map = new HashMap<String, Boolean>();

    private File root;

    public SearchFiles(File root){
        this.root = root;
    }

    /**
     * List eligible files on current path
     * @param directory
     *      The directory to be searched
     * @return
     *      Eligible files
     */
    private String[] getTargetFiles(File directory){
        if(directory == null){
            return null;
        }

        String[] files = directory.list(new FilenameFilter(){

            @Override
            public boolean accept(File dir, String name) {
                // TODO Auto-generated method stub
                return name.startsWith("Temp") && name.endsWith(".txt");
            }

        });

        return files;
    }

    /**
     * Print all eligible files
     */
    private void printFiles(String[] targets){
        for(String target: targets){
            System.out.println(target);
        }
    }
}
公共类搜索文件{
//它在dfs中使用
私有映射映射=新的HashMap();
私有文件根;
公共搜索文件(文件根目录){
this.root=根;
}
/**
*列出当前路径上符合条件的文件
*@param目录
*要搜索的目录
*@返回
*合格文件
*/
私有字符串[]GetTargetFile(文件目录){
if(目录==null){
返回null;
}
String[]files=directory.list(新文件名过滤器(){
@凌驾
公共布尔接受(文件目录,字符串名称){
//TODO自动生成的方法存根
返回name.startsWith(“Temp”)和name.endsWith(“.txt”);
}
});
归还文件;
}
/**
*打印所有符合条件的文件
*/
私有void打印文件(字符串[]目标){
for(字符串目标:目标){
系统输出打印项次(目标);
}
}
}
我将演示如何使用递归bfsdfs完成工作

递归的

    /**
 * How many files in the parent directory and its subdirectory <br>
 * depends on how many files in each subdirectory and their subdirectory
 */
private void recursive(File path){

    printFiles(getTargetFiles(path));
    for(File file: path.listFiles()){
        if(file.isDirectory()){
            recursive(file);
        }
    }
    if(path.isDirectory()){
        printFiles(getTargetFiles(path));
    }
}

public static void main(String args[]){
    SearchFiles searcher = new SearchFiles(new File("C:\\example"));
    searcher.recursive(searcher.root);
}
/**
 * Search the node's neighbors firstly before moving to the next level neighbors
 */
private void bfs(){
    if(root == null){
        return;
    }

    Queue<File> queue = new LinkedList<File>();
    queue.add(root);

    while(!queue.isEmpty()){
        File node = queue.remove();
        printFiles(getTargetFiles(node));
        File[] childs = node.listFiles(new FileFilter(){

            @Override
            public boolean accept(File pathname) {
                // TODO Auto-generated method stub
                if(pathname.isDirectory())
                    return true;

                return false;
            }

        });

        if(childs != null){
            for(File child: childs){
                queue.add(child);
            }
        }
    }
}

public static void main(String args[]){
    SearchFiles searcher = new SearchFiles(new File("C:\\example"));
    searcher.bfs();
}
 /**
 * Search as far as possible along each branch before backtracking
 */
private void dfs(){

    if(root == null){
        return;
    }

    Stack<File> stack = new Stack<File>();
    stack.push(root);
    map.put(root.getAbsolutePath(), true);
    while(!stack.isEmpty()){
        File node = stack.peek();
        File child = getUnvisitedChild(node);

        if(child != null){
            stack.push(child);
            printFiles(getTargetFiles(child));
            map.put(child.getAbsolutePath(), true);
        }else{
            stack.pop();
        }

    }
}

/**
 * Get unvisited node of the node
 * 
 */
private File getUnvisitedChild(File node){

    File[] childs = node.listFiles(new FileFilter(){

        @Override
        public boolean accept(File pathname) {
            // TODO Auto-generated method stub
            if(pathname.isDirectory())
                return true;

            return false;
        }

    });

    if(childs == null){
        return null;
    }

    for(File child: childs){

        if(map.containsKey(child.getAbsolutePath()) == false){
            map.put(child.getAbsolutePath(), false);
        }

        if(map.get(child.getAbsolutePath()) == false){
            return child; 
        }
    }

    return null;
}

public static void main(String args[]){
    SearchFiles searcher = new SearchFiles(new File("C:\\example"));
    searcher.dfs();
}
/**
*父目录及其子目录中有多少文件
*取决于每个子目录及其子目录中的文件数 */ 私有无效递归(文件路径){ 打印文件(getTargetFile(path)); 对于(文件:path.listFiles()){ if(file.isDirectory()){ 递归(文件); } } if(path.isDirectory()){ 打印文件(getTargetFile(path)); } } 公共静态void main(字符串参数[]){ SearchFiles searcher=新的SearchFiles(新文件(“C:\\example”); 递归(searcher.root); }
广度优先搜索

    /**
 * How many files in the parent directory and its subdirectory <br>
 * depends on how many files in each subdirectory and their subdirectory
 */
private void recursive(File path){

    printFiles(getTargetFiles(path));
    for(File file: path.listFiles()){
        if(file.isDirectory()){
            recursive(file);
        }
    }
    if(path.isDirectory()){
        printFiles(getTargetFiles(path));
    }
}

public static void main(String args[]){
    SearchFiles searcher = new SearchFiles(new File("C:\\example"));
    searcher.recursive(searcher.root);
}
/**
 * Search the node's neighbors firstly before moving to the next level neighbors
 */
private void bfs(){
    if(root == null){
        return;
    }

    Queue<File> queue = new LinkedList<File>();
    queue.add(root);

    while(!queue.isEmpty()){
        File node = queue.remove();
        printFiles(getTargetFiles(node));
        File[] childs = node.listFiles(new FileFilter(){

            @Override
            public boolean accept(File pathname) {
                // TODO Auto-generated method stub
                if(pathname.isDirectory())
                    return true;

                return false;
            }

        });

        if(childs != null){
            for(File child: childs){
                queue.add(child);
            }
        }
    }
}

public static void main(String args[]){
    SearchFiles searcher = new SearchFiles(new File("C:\\example"));
    searcher.bfs();
}
 /**
 * Search as far as possible along each branch before backtracking
 */
private void dfs(){

    if(root == null){
        return;
    }

    Stack<File> stack = new Stack<File>();
    stack.push(root);
    map.put(root.getAbsolutePath(), true);
    while(!stack.isEmpty()){
        File node = stack.peek();
        File child = getUnvisitedChild(node);

        if(child != null){
            stack.push(child);
            printFiles(getTargetFiles(child));
            map.put(child.getAbsolutePath(), true);
        }else{
            stack.pop();
        }

    }
}

/**
 * Get unvisited node of the node
 * 
 */
private File getUnvisitedChild(File node){

    File[] childs = node.listFiles(new FileFilter(){

        @Override
        public boolean accept(File pathname) {
            // TODO Auto-generated method stub
            if(pathname.isDirectory())
                return true;

            return false;
        }

    });

    if(childs == null){
        return null;
    }

    for(File child: childs){

        if(map.containsKey(child.getAbsolutePath()) == false){
            map.put(child.getAbsolutePath(), false);
        }

        if(map.get(child.getAbsolutePath()) == false){
            return child; 
        }
    }

    return null;
}

public static void main(String args[]){
    SearchFiles searcher = new SearchFiles(new File("C:\\example"));
    searcher.dfs();
}
/**
*在移动到下一级邻居之前,首先搜索节点的邻居
*/
私人银行{
if(root==null){
返回;
}
Queue Queue=new LinkedList();
添加(根);
而(!queue.isEmpty()){
文件节点=queue.remove();
打印文件(getTargetFile(节点));
File[]childs=node.listFiles(新文件过滤器(){
@凌驾
公共布尔接受(文件路径名){
//TODO自动生成的方法存根
if(路径名.isDirectory())
返回true;
返回false;
}
});
if(childs!=null){
用于(文件子项:childs){
添加(子级);
}
}
}
}
公共静态void main(字符串参数[]){
SearchFiles searcher=新的SearchFiles(新文件(“C:\\example”);
searcher.bfs();
}
深度优先搜索

    /**
 * How many files in the parent directory and its subdirectory <br>
 * depends on how many files in each subdirectory and their subdirectory
 */
private void recursive(File path){

    printFiles(getTargetFiles(path));
    for(File file: path.listFiles()){
        if(file.isDirectory()){
            recursive(file);
        }
    }
    if(path.isDirectory()){
        printFiles(getTargetFiles(path));
    }
}

public static void main(String args[]){
    SearchFiles searcher = new SearchFiles(new File("C:\\example"));
    searcher.recursive(searcher.root);
}
/**
 * Search the node's neighbors firstly before moving to the next level neighbors
 */
private void bfs(){
    if(root == null){
        return;
    }

    Queue<File> queue = new LinkedList<File>();
    queue.add(root);

    while(!queue.isEmpty()){
        File node = queue.remove();
        printFiles(getTargetFiles(node));
        File[] childs = node.listFiles(new FileFilter(){

            @Override
            public boolean accept(File pathname) {
                // TODO Auto-generated method stub
                if(pathname.isDirectory())
                    return true;

                return false;
            }

        });

        if(childs != null){
            for(File child: childs){
                queue.add(child);
            }
        }
    }
}

public static void main(String args[]){
    SearchFiles searcher = new SearchFiles(new File("C:\\example"));
    searcher.bfs();
}
 /**
 * Search as far as possible along each branch before backtracking
 */
private void dfs(){

    if(root == null){
        return;
    }

    Stack<File> stack = new Stack<File>();
    stack.push(root);
    map.put(root.getAbsolutePath(), true);
    while(!stack.isEmpty()){
        File node = stack.peek();
        File child = getUnvisitedChild(node);

        if(child != null){
            stack.push(child);
            printFiles(getTargetFiles(child));
            map.put(child.getAbsolutePath(), true);
        }else{
            stack.pop();
        }

    }
}

/**
 * Get unvisited node of the node
 * 
 */
private File getUnvisitedChild(File node){

    File[] childs = node.listFiles(new FileFilter(){

        @Override
        public boolean accept(File pathname) {
            // TODO Auto-generated method stub
            if(pathname.isDirectory())
                return true;

            return false;
        }

    });

    if(childs == null){
        return null;
    }

    for(File child: childs){

        if(map.containsKey(child.getAbsolutePath()) == false){
            map.put(child.getAbsolutePath(), false);
        }

        if(map.get(child.getAbsolutePath()) == false){
            return child; 
        }
    }

    return null;
}

public static void main(String args[]){
    SearchFiles searcher = new SearchFiles(new File("C:\\example"));
    searcher.dfs();
}
/**
*回溯之前,尽可能沿每个分支搜索
*/
私有无效dfs(){
if(root==null){
返回;
}
堆栈=新堆栈();
栈.推(根);
map.put(root.getAbsolutePath(),true);
而(!stack.isEmpty()){
文件节点=stack.peek();
File child=getUnvisitedChild(节点);
if(child!=null){
栈.推(子);
打印文件(getTargetFile(子文件));
map.put(child.getAbsolutePath(),true);
}否则{
stack.pop();
}
}
}
/**
*获取节点的未访问节点
* 
*/
私有文件getUnvisitedChild(文件节点){
File[]childs=node.listFiles(新文件过滤器(){
@凌驾
公共布尔接受(文件路径名){
//TODO自动生成的方法存根
if(路径名.isDirectory())
返回true;
返回false;
}
});
if(childs==null){
返回null;
}
用于(文件子项:childs){
if(map.containsKey(child.getAbsolutePath())==false){
map.put(child.getAbsolutePath(),false);
}
if(map.get(child.getAbsolutePath())==false){
返回儿童;
}
}
返回null;
}
公共静态void main(字符串参数[]){
SearchFiles searcher=新的SearchFiles(新文件(“C:\\example”);
searcher.dfs();
}

我知道,这是一个老问题。但为了完整起见,lambda版本

File dir = new File(directory);
File[] files = dir.listFiles((dir1, name) -> name.startsWith("temp") && name.endsWith(".txt"));
详述,Apache IO UTILS可能会节省您一些时间。请考虑下面的示例,该示例将递归搜索给定名称的文件:

    File file = FileUtils.listFiles(new File("the/desired/root/path"), 
                new NameFileFilter("filename.ext"), 
                FileFilterUtils.trueFileFilter()
            ).iterator().next();
见: