处理不需要的路径会导致路径/文件搜索

时间:2014-05-06 12:47:17

标签: java

我有一个文本文件,它是java中递归文件搜索的结果。它使用if语句(使用Path.class的一个或多个扩展)搜索特定文件类型的所需路径,并记录所述路径,包括文本文件中的文件名。最终结果是符合条件的所有路径和文件名列表。

我遇到的问题是我希望路径中有某些目录:

a)从生成的文本文件中删除。

b)阻止它们首先出现在文本文件中。

以下是代码:

import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.*;

import static java.nio.file.FileVisitResult.*;
import static java.nio.file.FileVisitOption.*;

import java.util.*;

public class Find {

    public static class Finder
        extends SimpleFileVisitor<Path> {

        private final PathMatcher matcher;
        private int numMatches = 0;

        Finder(String pattern) {
        matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
        }

        // Compares the glob pattern against
        // the file or directory name.
        void find(Path file) throws IOException {

            Path name = file.getFileName();
            try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("ImageList.txt",true)))){

                if ((name != null) && (matcher.matches(name))) {
                    numMatches++;
                    out.write(file.toString());
                    out.write("\r\n\r\n");
                    out.flush();
                    out.close();
                    System.out.println(file + "\n");
                }


            }catch (IOException e){
                 //Exception handling placeholder
            }                 

        }

        // Prints the total number of
        // matches to standard out.
        void done() {
            System.out.println("Matched: " + numMatches);
        }

        // Invoke the pattern matching
        // method on each file.
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            find(file);
            return CONTINUE;
        }

        // Invoke the pattern matching
        // method on each directory.
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            find(dir);
            return CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) {
            System.err.println(exc);
            return CONTINUE;
        }
    }

    static void usage() {
        System.err.println("java Find <path>" + " -name \"<glob_pattern>\"");
        System.exit(-1);
    }

    public static void main(String[] args) throws IOException {

        if (args.length < 3 || !args[1].equals("-name"))
            usage();

        Path startingDir = Paths.get(args[0]);
        String pattern = args[2];
        Finder finder = new Finder(pattern);
        Files.walkFileTree(startingDir, finder);
        finder.done();
    }
}

2 个答案:

答案 0 :(得分:0)

如果您使用java.nio.file中的课程,则可以使用Glob过滤结果或编写自己的DirectoryFilter

<强> Filtering a Directory Listing By Using Globbing

  

如果您只想获取每个名称所在的文件和子目录   匹配特定模式,您可以使用   newDirectoryStream(Path,String)方法,它提供了一个内置的   全球过滤器。如果您不熟悉glob语法,请参阅什么是   通配?

     

例如,以下代码段列出了与Java相关的文件:   .class.java.jar个文件。:

Path dir = ...;
try (DirectoryStream<Path> stream =
     Files.newDirectoryStream(dir, "*.{java,class,jar}")) {
    for (Path entry: stream) {
        System.out.println(entry.getFileName());
    }
} catch (IOException x) {
    // IOException can never be thrown by the iteration.
    // In this snippet, it can // only be thrown by newDirectoryStream.
    System.err.println(x);
}

<强> Writing Your Own Directory Filter

  

也许您想根据某些内容过滤目录的内容   模式匹配以外的条件。您可以创建自己的过滤器   通过实现DirectoryStream.Filter<T>接口。这个   接口由一个方法,accept,它决定是否一个   文件满足搜索要求。

     

例如,以下代码段实现了一个过滤器   仅检索目录:

DirectoryStream.Filter<Path> filter =
    newDirectoryStream.Filter<Path>() {
    public boolean accept(Path file) throws IOException {
        try {
            return (Files.isDirectory(path));
        } catch (IOException x) {
            // Failed to determine if it's a directory.
            System.err.println(x);
            return false;
        }
    }
};

答案 1 :(得分:0)

好的,我们现在已经弄明白了。对于任何好奇的人:

import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.*;

import static java.nio.file.FileVisitResult.*;
import static java.nio.file.FileVisitOption.*;

import java.util.*;

public class Find {

    public static class Finder
        extends SimpleFileVisitor<Path> {

        private final PathMatcher matcher;
        private int numMatches = 0;

        Finder(String pattern) {
            matcher = FileSystems.getDefault()
                    .getPathMatcher("glob:" + pattern);
        }

        // Compares the glob pattern against
        // the file or directory name.
        void find(Path file) throws IOException {
            String path = file.toString();
            path = path.toUpperCase();
            if(!path.contains("D:\\users\\mg\\workspace\\bin".toUpperCase()) && !path.contains("D:\\users\\mg\\workspace\\build".toUpperCase())){

                    Path name = file.getFileName();
                try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("ImageList.txt",true)))){

                    if ((name != null) && (matcher.matches(name))) {

                    numMatches++;
                    out.write(file.toString());
                    out.write("\r\n\r\n");
                    out.flush();
                    out.close();
                        System.out.println(file + "\n");
                    }


                }catch (IOException e){
                    //Exception handling placeholder
                }                 
            }

        }


        // Prints the total number of
        // matches to standard out.
        void done() {
            System.out.println("Matched: "
                + numMatches);
        }

        // Invoke the pattern matching
        // method on each file.
        @Override
        public FileVisitResult visitFile(Path file,
                BasicFileAttributes attrs) throws IOException {
            find(file);
            return CONTINUE;
        }

        // Invoke the pattern matching
        // method on each directory.
        @Override
        public FileVisitResult preVisitDirectory(Path dir,
                BasicFileAttributes attrs) throws IOException {
            find(dir);
            return CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file,
                IOException exc) {
            System.err.println(exc);
            return CONTINUE;
        }
    }

    static void usage() {
        System.err.println("java Find <path>" +
            " -name \"<glob_pattern>\"");
        System.exit(-1);
    }

    public static void main(String[] args)
        throws IOException {

        if (args.length < 3 || !args[1].equals("-name"))
            usage();

        Path startingDir = Paths.get(args[0]);
        String pattern = args[2];

        Finder finder = new Finder(pattern);
        Files.walkFileTree(startingDir, finder);
        finder.done();

    }
}