programing

Java에서 와일드카드 문자열과 일치하는 파일을 찾으려면 어떻게 해야 합니까?

sourcejob 2022. 9. 29. 00:14
반응형

Java에서 와일드카드 문자열과 일치하는 파일을 찾으려면 어떻게 해야 합니까?

이건 정말 간단해.다음과 같은 문자열이 있는 경우:

../Test?/sample*.txt

하는 파일 인 방법은 (를 들어, 이 과 일치하는 파일 목록이 있어야 .)../Test1/sample22b.txt ★★★★★★★★★★★★★★★★★」../Test4/sample-spiffy.txt 아니다../Test3/sample2.blah ★★★★★★★★★★★★★★★★★」../Test44/sample2.txt)

살펴보니 적절한 것 같지만 상대적인 디렉토리 경로에서 파일을 찾는 데 어떻게 사용해야 할지 잘 모르겠습니다.

와일드카드 구문을 사용하기 때문에 개미의 출처를 찾을 수 있을 것 같습니다만, 여기서 확실히 알 수 없는 것이 있습니다.

(edit: 위의 예는 샘플 케이스에 불과합니다.실행 시 와일드카드를 포함하는 일반 경로를 구문 분석하는 방법을 찾고 있습니다.주인님 제안으로 방법을 알아냈는데 좀 짜증나네요.Java JRE는 단일 인수에서 메인(String[] 인수)의 간단한 와일드카드를 자동으로 해석하여 시간과 번거로움을 덜어주는 것은 말할 것도 없습니다.파일 이외의 논쟁이 혼재하지 않아서 다행입니다.)

Apache commons-io에서 시도합니다(listFiles ★★★★★★★★★★★★★★★★★」iterateFiles( 드 : 。

File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("sample*.java");
File[] files = dir.listFiles(fileFilter);
for (int i = 0; i < files.length; i++) {
   System.out.println(files[i]);
}

TestX을 먼저 합니다: 더더 、 저저 、 저저 、 먼저 : folders:: 。

File[] dirs = new File(".").listFiles(new WildcardFileFilter("Test*.java");
for (int i=0; i<dirs.length; i++) {
   File dir = dirs[i];
   if (dir.isDirectory()) {
       File[] files = dir.listFiles(new WildcardFileFilter("sample*.java"));
   }
}

상당한 '뇌력' 솔루션이지만 잘 작동해야 합니다.이것이 사용자의 요구에 맞지 않는 경우 RegexFileFilter를 언제든지 사용할 수 있습니다.

Apache Ant의 DirectoryScanner를 검토합니다.

DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{"**/*.java"});
scanner.setBasedir("C:/Temp");
scanner.setCaseSensitive(false);
scanner.scan();
String[] files = scanner.getIncludedFiles();

ant.jar(개미 1.7.1의 경우 약 1.3MB)를 참조해야 합니다.

다음은 Java 7 nio globing 및 Java 8 lamda에서 실행되는 패턴별로 파일을 나열하는 예입니다.

    try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(
            Paths.get(".."), "Test?/sample*.txt")) {
        dirStream.forEach(path -> System.out.println(path));
    }

또는

    PathMatcher pathMatcher = FileSystems.getDefault()
        .getPathMatcher("regex:Test./sample\\w+\\.txt");
    try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(
            new File("..").toPath(), pathMatcher::matches)) {
        dirStream.forEach(path -> System.out.println(path));
    }

8에서는 Java 8 을 할 수 있습니다.Files#find직직 directly directly java.nio.file.

public static Stream<Path> find(Path start,
                                int maxDepth,
                                BiPredicate<Path, BasicFileAttributes> matcher,
                                FileVisitOption... options)

사용 예

Files.find(startingPath,
           Integer.MAX_VALUE,
           (path, basicFileAttributes) -> path.toFile().getName().matches(".*.pom")
);

의 String과 함께 사용할 수 .matches과 같습니다예를 들어 다음과 같습니다.

String original = "../Test?/sample*.txt";
String regex = original.replace("?", ".?").replace("*", ".*?");

이것은, 다음의 예에 유효합니다.

Assert.assertTrue("../Test1/sample22b.txt".matches(regex));
Assert.assertTrue("../Test4/sample-spiffy.txt".matches(regex));

반증 사례:

Assert.assertTrue(!"../Test3/sample2.blah".matches(regex));
Assert.assertTrue(!"../Test44/sample2.txt".matches(regex));

지금은 도움이 되지 않을 수 있지만 JDK 7은 "NIO 기능 추가"의 일부로 glob 및 regex 파일 이름을 일치시키는 것을 의도하고 있습니다.

와일드카드 라이브러리는 glob 및 regex 파일 이름 조회를 효율적으로 수행합니다.

http://code.google.com/p/wildcard/

실장은 간결합니다.JAR은 12.9킬로바이트에 불과합니다.

외부 가져오기를 사용하지 않는 간단한 방법은 이 방법을 사용하는 것입니다.

billing_201208.csv, billing_201209.csv, billing_201210.csv라는 이름의 csv 파일을 작성했는데 정상적으로 동작하고 있는 것 같습니다.

위의 파일이 존재하는 경우 출력은 다음과 같습니다.

found billing_201208.csv
found billing_201209.csv
found billing_201210.csv

//Import -> java.io 를 사용합니다.파일public static void main(String[] args) {문자열 경로ToScan = ".;문자열 target_file; // file That You Want To Filter파일 폴더ToScan = 새 파일(pathToScan);

    File[] listOfFiles = folderToScan.listFiles();

     for (int i = 0; i < listOfFiles.length; i++) {
            if (listOfFiles[i].isFile()) {
                target_file = listOfFiles[i].getName();
                if (target_file.startsWith("billing")
                     && target_file.endsWith(".csv")) {
                //You can add these files to fileList by using "list.add" here
                     System.out.println("found" + " " + target_file); 
                }
           }
     }    
}

다른 답변에 게재된 바와 같이 와일드카드 라이브러리는 glob 파일명과 regex 파일명의 매칭에 대해 기능합니다.http://code.google.com/p/wildcard/

*nix 스타일의 파일 시스템에서 절대 및 상대적인 글로벌 패턴을 매칭하기 위해 다음 코드를 사용했습니다.

String filePattern = String baseDir = "./";
// If absolute path. TODO handle windows absolute path?
if (filePattern.charAt(0) == File.separatorChar) {
    baseDir = File.separator;
    filePattern = filePattern.substring(1);
}
Paths paths = new Paths(baseDir, filePattern);
List files = paths.getFiles();

Apache commons io 라이브러리에서 FileUtils.listFiles 메서드를 얻으려고 했지만(Vladimir의 답변 참조) 성공하지 못했습니다(지금은 한 번에 하나의 디렉토리 또는 파일에 일치하는 패턴만 처리할 수 있다는 것을 깨달았습니다).

또한 파일 시스템 전체를 검색하지 않고 임의의 사용자가 제공한 절대 타입의 글로벌 패턴을 처리하기 위해 regex 필터(Fabian의 답변 참조)를 사용하는 경우 가장 큰 non-regex/glob 프레픽스를 결정하기 위해 제공된 글로벌의 전처리가 필요합니다.

물론 Java 7은 요청된 기능을 잘 처리할 수 있지만, 유감스럽게도 지금은 Java 6에 얽매여 있습니다.그 도서관은 크기가 13.5KB로 비교적 작다.

리뷰어에 대한 주의사항:이 라이브러리를 언급하는 기존 답변에 위의 내용을 추가하려고 했으나 편집이 거부되었습니다.저도 댓글 달기에는 부족해요.더 좋은 방법은 없을까?

를 사용할 수 있어야 합니다.WildcardFileFilter. 그냥 사용하세요.System.getProperty("user.dir")작업 디렉토리를 가져옵니다.이것을 시험해 보세요.

public static void main(String[] args) {
File[] files = (new File(System.getProperty("user.dir"))).listFiles(new WildcardFileFilter(args));
//...
}

교환할 필요가 없습니다.*와 함께[.*]와일드카드 필터가 를 사용하고 있는 경우java.regex.Pattern테스트한 적은 없지만 패턴과 파일 필터를 계속 사용하고 있습니다.

Glob of Java7: 파일 검색(샘플)

Apache 필터는 알려진 디렉터리에서 파일을 반복하도록 구축되었습니다.디렉토리 내에서도 와일드카드를 허용하려면 에서 경로를 분할해야 합니다.\또는/그리고 각 부분에 필터를 따로 붙입니다.

Java 스트림만 사용

Path testPath = Paths.get("C:\");

Stream<Path> stream =
                Files.find(testPath, 1,
                        (path, basicFileAttributes) -> {
                            File file = path.toFile();
                            return file.getName().endsWith(".java");
                        });

// Print all files found
stream.forEach(System.out::println);

를 사용하여 다음과 같은 작업을 수행하는 것은 어떨까요?

File myRelativeDir = new File("../../foo");
String fullPath = myRelativeDir.getCanonicalPath();
Sting wildCard = fullPath + File.separator + "*.txt";

// now you have a fully qualified path

그러면 상대 경로를 걱정할 필요가 없으며 필요에 따라 와일드카드를 사용할 수 있습니다.

JDK FileVisitor 인터페이스를 구현합니다.http://wilddiary.com/list-files-matching-a-naming-pattern-java/ 의 예를 다음에 나타냅니다.

사용방법:

public static boolean isFileMatchTargetFilePattern(final File f, final String targetPattern) {
        String regex = targetPattern.replace(".", "\\.");  //escape the dot first
        regex = regex.replace("?", ".?").replace("*", ".*");
        return f.getName().matches(regex);

    }

jUnit 테스트:

@Test
public void testIsFileMatchTargetFilePattern()  {
    String dir = "D:\\repository\\org\my\\modules\\mobile\\mobile-web\\b1605.0.1";
    String[] regexPatterns = new String[] {"_*.repositories", "*.pom", "*-b1605.0.1*","*-b1605.0.1", "mobile*"};
    File fDir = new File(dir);
    File[] files = fDir.listFiles();

    for (String regexPattern : regexPatterns) {
        System.out.println("match pattern [" + regexPattern + "]:");
        for (File file : files) {
            System.out.println("\t" + file.getName() + " matches:" + FileUtils.isFileMatchTargetFilePattern(file, regexPattern));
        }
    }
}

출력:

match pattern [_*.repositories]:
    mobile-web-b1605.0.1.pom matches:false
    mobile-web-b1605.0.1.war matches:false
    _remote.repositories matches:true
match pattern [*.pom]:
    mobile-web-b1605.0.1.pom matches:true
    mobile-web-b1605.0.1.war matches:false
    _remote.repositories matches:false
match pattern [*-b1605.0.1*]:
    mobile-web-b1605.0.1.pom matches:true
    mobile-web-b1605.0.1.war matches:true
    _remote.repositories matches:false
match pattern [*-b1605.0.1]:
    mobile-web-b1605.0.1.pom matches:false
    mobile-web-b1605.0.1.war matches:false
    _remote.repositories matches:false
match pattern [mobile*]:
    mobile-web-b1605.0.1.pom matches:true
    mobile-web-b1605.0.1.war matches:true
    _remote.repositories matches:false

io 라이브러리의 파일 클래스를 사용하는 가장 간단하고 쉬운 방법은 다음과 같습니다.

    String startingdir="The directory name";
    String filenameprefix="The file pattern"
    File startingDirFile=new File(startingdir); 
    final File[] listFiles=startingDirFile.listFiles(new FilenameFilter() {
        public boolean accept(File arg0,String arg1)
        {System.out.println(arg0+arg1);
            return arg1.matches(filenameprefix);}
        });
    System.out.println(Arrays.toString(listFiles));

언급URL : https://stackoverflow.com/questions/794381/how-to-find-files-that-match-a-wildcard-string-in-java

반응형