BAEL 7277 - Find Files by Extension in Specified Directory in Java (#15356)

* new module: libraries-7

* ready for review
This commit is contained in:
Ulisses Lima 2023-12-17 07:50:31 -03:00 committed by GitHub
parent 0b8873f03e
commit 3b2d6c5335
11 changed files with 302 additions and 1 deletions

View File

@ -17,4 +17,4 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m
- [Using libphonenumber to Validate Phone Numbers](https://www.baeldung.com/java-libphonenumber)
- [Apache Commons Collections vs Google Guava](https://www.baeldung.com/apache-commons-collections-vs-guava)
- [Guide to Using ModelMapper](https://www.baeldung.com/java-modelmapper)
- More articles [[<-- prev]](/libraries-5)
- More articles [[<-- prev]](/libraries-5) [[next -->]](/libraries-7)

11
libraries-7/README.md Normal file
View File

@ -0,0 +1,11 @@
## Libraries-7
This module contains articles about various Java libraries.
These are small libraries that are relatively easy to use and do not require any separate module of their own.
The code examples related to different libraries are each in their own module.
Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-modules) we already have separate modules. Please make sure to have a look at the existing modules in such cases.
### Relevant articles
- More articles [[<-- prev]](/libraries-6)

22
libraries-7/pom.xml Normal file
View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>libraries-7</artifactId>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,29 @@
package com.baeldung.findfiles;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
public class FindFileApacheUtils {
private FindFileApacheUtils() {
}
public static Iterator<File> find(Path startPath, String extension) {
if (!Files.isDirectory(startPath)) {
throw new IllegalArgumentException("Provided path is not a directory: " + startPath);
}
if (!extension.startsWith("."))
extension = "." + extension;
return FileUtils.iterateFiles(startPath.toFile(), WildcardFileFilter.builder()
.setWildcards("*" + extension)
.get(), TrueFileFilter.INSTANCE);
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.findfiles;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class FindFileJava2Utils {
private FindFileJava2Utils() {
}
public static List<File> find(File startPath, String extension) {
if (!startPath.isDirectory()) {
throw new IllegalArgumentException("Provided path is not a directory: " + startPath);
}
List<File> matches = new ArrayList<>();
File[] files = startPath.listFiles();
if (files == null)
return matches;
MatchExtensionPredicate filter = new MatchExtensionPredicate(extension);
for (File file : files) {
if (file.isDirectory()) {
matches.addAll(find(file, extension));
} else if (filter.test(file.toPath())) {
matches.add(file);
}
}
return matches;
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.findfiles;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
public class FindFileJava7Utils {
private FindFileJava7Utils() {
}
public static List<Path> find(Path startPath, String extension) throws IOException {
if (!Files.isDirectory(startPath)) {
throw new IllegalArgumentException("Provided path is not a directory: " + startPath);
}
final List<Path> matches = new ArrayList<>();
MatchExtensionPredicate filter = new MatchExtensionPredicate(extension);
Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
if (filter.test(file)) {
matches.add(file);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
return FileVisitResult.CONTINUE;
}
});
return matches;
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.findfiles;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.function.Consumer;
public class FindFileJava8Utils {
private FindFileJava8Utils() {
}
public static void find(Path startPath, String extension, Consumer<Path> consumer) throws IOException {
if (!Files.isDirectory(startPath)) {
throw new IllegalArgumentException("Provided path is not a directory: " + startPath);
}
MatchExtensionPredicate filter = new MatchExtensionPredicate(extension);
Files.walkFileTree(startPath, new SimpleFileConsumerVisitor(filter, consumer));
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.findfiles;
import java.nio.file.Path;
import java.util.function.Predicate;
public class MatchExtensionPredicate implements Predicate<Path> {
private final String extension;
public MatchExtensionPredicate(String extension) {
if (!extension.startsWith("."))
extension = "." + extension;
this.extension = extension.toLowerCase();
}
@Override
public boolean test(Path path) {
if (path == null)
return false;
return path.getFileName()
.toString()
.toLowerCase()
.endsWith(extension);
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.findfiles;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.function.Consumer;
import java.util.function.Predicate;
public class SimpleFileConsumerVisitor extends SimpleFileVisitor<Path> {
private final Predicate<Path> filter;
private final Consumer<Path> consumer;
public SimpleFileConsumerVisitor(MatchExtensionPredicate filter, Consumer<Path> consumer) {
this.filter = filter;
this.consumer = consumer;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
if (filter.test(file))
consumer.accept(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
}

View File

@ -0,0 +1,79 @@
package com.baeldung.findfiles;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class FindFileUtilsIntegrationTest {
private static final String TEST_EXTENSION = ".test";
private static final String OTHER_EXTENSION = ".other";
private static final List<Path> TEST_FILES = new ArrayList<>();
private static final List<Path> OTHER_FILES = new ArrayList<>();
private static Path TEST_DIR;
@BeforeAll
static void setup() throws IOException {
TEST_DIR = Files.createTempDirectory(null);
final Path nestedDir = TEST_DIR.resolve("sub-dir");
Files.createDirectories(nestedDir);
TEST_FILES.add(Files.createFile(TEST_DIR.resolve("a" + TEST_EXTENSION)));
OTHER_FILES.add(Files.createFile(TEST_DIR.resolve("a" + OTHER_EXTENSION)));
TEST_FILES.add(Files.createFile(nestedDir.resolve("b" + TEST_EXTENSION)));
OTHER_FILES.add(Files.createFile(nestedDir.resolve("b" + OTHER_EXTENSION)));
}
@AfterAll
static void cleanUp() {
FileUtils.deleteQuietly(TEST_DIR.toFile());
}
@Test
void whenFindFilesWithJava2_thenOnlyMatchingFilesFound() {
List<File> matches = FindFileJava2Utils.find(TEST_DIR.toFile(), TEST_EXTENSION);
assertEquals(TEST_FILES.size(), matches.size());
}
@Test
void whenFindFilesWithJava7_thenOnlyMatchingFilesFound() throws IOException {
List<Path> matches = FindFileJava7Utils.find(TEST_DIR, TEST_EXTENSION);
assertEquals(TEST_FILES.size(), matches.size());
}
@Test
void whenFindFilesWithJava8_thenOnlyMatchingFilesFound() throws IOException {
final AtomicInteger matches = new AtomicInteger(0);
FindFileJava8Utils.find(TEST_DIR, TEST_EXTENSION, path -> matches.incrementAndGet());
assertEquals(TEST_FILES.size(), matches.get());
}
@Test
void whenFindFilesWithApache_thenOnlyMatchingFilesFound() {
final AtomicInteger matches = new AtomicInteger(0);
Iterator<File> iterator = FindFileApacheUtils.find(TEST_DIR, TEST_EXTENSION);
iterator.forEachRemaining(file -> matches.incrementAndGet());
assertEquals(TEST_FILES.size(), matches.get());
}
}

View File

@ -771,6 +771,7 @@
<module>libraries-4</module>
<module>libraries-5</module>
<module>libraries-6</module>
<module>libraries-7</module>
<module>libraries-ai</module>
<module>libraries-apache-commons-2</module>
<module>libraries-apache-commons-collections</module>
@ -1021,6 +1022,7 @@
<module>libraries-4</module>
<module>libraries-5</module>
<module>libraries-6</module>
<module>libraries-7</module>
<module>libraries-ai</module>
<module>libraries-apache-commons-2</module>
<module>libraries-apache-commons-collections</module>