Java find files starting with

Listing All Files in a Directory in Java

Learn to use various Java APIs such as Files.list() and DirectoryStream to list all files present in a directory, including hidden files, recursively.

  • For using external iteration (for loop) use DirectoryStream .
  • For using Stream API operations, use Files.list() instead.

1. Listing Files Only in a Given Directory

1.1. Sream of Files with Files.list()

If we are interested in non-recursively listing the files and excluding all sub-directories and files in sub-directories, then we can use this approach.

  • Read all files and directories entries using Files.list().
  • Check if a given entry is a file using PredicateFile::isFile.
  • Collect all filtered entries into a List.
//The source directory String directory = "C:/temp"; // Reading only files in the directory try < Listfiles = Files.list(Paths.get(directory)) .map(Path::toFile) .filter(File::isFile) .collect(Collectors.toList()); files.forEach(System.out::println); > catch (IOException e)

1.2. DirectoryStream to Loop through Files

DirectoryStream is part of Java 7 and is used to iterate over the entries in a directory in for-each loop style.

Closing a directory stream releases any resources associated with the stream. Failure to close the stream may result in a resource leak. The try-with-resources statement provides a useful construct to ensure that the stream is closed.

List fileList = new ArrayList<>(); try (DirectoryStream stream = Files .newDirectoryStream(Paths.get(directory))) < for (Path path : stream) < if (!Files.isDirectory(path)) < fileList.add(path.toFile()); >> > fileList.forEach(System.out::println);

2. Listing All Files in Given Directory and Sub-directories

2.1. Files.walk() for Stream of Paths

The walk() method returns a Stream by walking the file tree beginning with a given starting file/directory in a depth-first manner.

Note that this method visits all levels of the file tree.

String directory = "C:/temp"; List pathList = new ArrayList<>(); try (Stream stream = Files.walk(Paths.get(directory))) < pathList = stream.map(Path::normalize) .filter(Files::isRegularFile) .collect(Collectors.toList()); >pathList.forEach(System.out::println);

If you wish to include the list of Path instances for directories as well, then remove the filter condition Files::isRegularFile.

We can also write the file tree walking logic using the recursion. It gives a little more flexibility if we want to perform some intermediate steps/checks before adding the entry to list of the files.

String directory = "C:/temp"; //Recursively list all files List fileList = listFiles(directory); fileList.forEach(System.out::println); private static List listFiles(final String directory) < if (directory == null) < return Collections.EMPTY_LIST; >List fileList = new ArrayList<>(); File[] files = new File(directory).listFiles(); for (File element : files) < if (element.isDirectory()) < fileList.addAll(listFiles(element.getPath())); >else < fileList.add(element); >> return fileList; >

Please note that if we’re working with a large directory, then using DirectoryStream performs better.

3. Listing All Files of a Certain Extention

Читайте также:  Тег MARQUEE, атрибут behavior

To get the list of all files of certain extensions only, use two predicates Files::isRegularFile and filename.endsWith(«.extension») together.

In given example, we are listing all .java files in a given directory and all of its sub-directories.

String directory = "C:/temp"; //Recursively list all files List pathList = new ArrayList<>(); try (Stream stream = Files.walk(Paths.get(directory))) < // Do something with the stream. pathList = stream.map(Path::normalize) .filter(Files::isRegularFile) .filter(path ->path.getFileName().toString().endsWith(".java")) .collect(Collectors.toList()); > pathList.forEach(System.out::println); >

4. Listing All Hidden Files

To find all the hidden files, we can use filter expression file -> file.isHidden() in any of the above examples.

List files = Files.list(Paths.get(dirLocation)) .filter(path -> path.toFile().isHidden()) .map(Path::toFile) .collect(Collectors.toList());

In the above examples, we learn to use the java 8 APIs loop through the files in a directory recursively using various search methods. Feel free to modify the code and play with it.

Источник

Файлы Java.найдите примеры

Java 8 `Файлы.найти” примеры поиска файлов по имени файла, размеру файла и времени последнего изменения.

Файлы .найти API доступен с Java 8. Он быстро выполняет поиск или находит файлы из дерева файлов.

  1. Файлы.найти() сигнатура метода
  2. Поиск файлов по имени файла
  3. Поиск файлов по размеру файла
  4. Поиск файлов по времени последнего изменения

В старые времена мы всегда использовали рекурсивный цикл, подверженный ошибкам, для обхода дерева файлов. Это Java 8 Это Java 8 это может сэкономить вам много времени.

1. Файлы.найти ( ) Подпись

Просмотрите Файлы.найдите() подпись.

public static Stream find(Path start, int maxDepth, BiPredicate matcher, FileVisitOption. options) throws IOException 
  • Путь , начальный файл или папка.
  • Параметр maxDepth определяет максимальное количество уровней каталога для поиска. Если мы положим 1 , что означает поиск только папки верхнего уровня или корневой папки, игнорируйте все ее вложенные папки; Если мы хотим выполнить поиск по всем уровням папок, поставьте Целое число. МАКСИМАЛЬНОЕ ЗНАЧЕНИЕ .
  • В BiPredicate предназначен для проверки условий или фильтрации.
  • Параметр FileVisitOption указывает, хотим ли мы переходить по символическим ссылкам, по умолчанию нет. Мы можем поставить FileVisitOption. FOLLOW_LINKS для перехода по символическим ссылкам.

2. Поиск файлов по имени файла

В этом примере используется Files.find() для поиска файлов, соответствующих имени файла google.png , начиная с папки C:\\test , и включал все уровни его вложенных папок.

package com.mkyong.io.api; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class FileFindExample1 < public static void main(String[] args) throws IOException < Path path = Paths.get("C:\\test"); Listresult = findByFileName(path, "google.png"); result.forEach(x -> System.out.println(x)); > public static List findByFileName(Path path, String fileName) throws IOException < Listresult; try (Stream pathStream = Files.find(path, Integer.MAX_VALUE, (p, basicFileAttributes) -> p.getFileName().toString().equalsIgnoreCase(fileName)) ) < result = pathStream.collect(Collectors.toList()); >return result; > > 

Мы также можем использовать Файлы API для дальнейшей проверки пути.

try (Stream pathStream = Files.find(path, Integer.MAX_VALUE, (p, basicFileAttributes) -> < // if directory or no-read permission, ignore if(Files.isDirectory(p) || !Files.isReadable(p))< return false; >return p.getFileName().toString().equalsIgnoreCase(fileName); >) ) 

3. Поиск файлов по размеру файла

В этом примере используется Files.find() для поиска файлов, размер которых больше или равен 100 МБ.

package com.mkyong.io.api; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class FileFindExample2 < public static void main(String[] args) throws IOException < Path path = Paths.get("C:\\Users\\mkyong\\Downloads"); long fileSize = 1024 * 1024 * 100; // 100M Listresult = findByFileSize(path, fileSize); for (Path p : result) < System.out.println(String.format("%-40s [fileSize]: %,d", p, Files.size(p))); >> public static List findByFileSize(Path path, long fileSize) throws IOException < Listresult; try (Stream pathStream = Files.find(path, Integer.MAX_VALUE, (p, basicFileAttributes) -> < try < if (Files.isDirectory(p)) < // ignore directory return false; >return Files.size(p) >= fileSize; > catch (IOException e) < System.err.println("Unable to get the file size of path : " + path); >return false; > )) < result = pathStream.collect(Collectors.toList()); >return result; > > 
C:\Users\mkyong\Downloads\hello.mp4 [fileSize]: 4,796,543,886 C:\Users\mkyong\Downloads\java.mp4.bk [fileSize]: 5,502,785,778 C:\Users\mkyong\Downloads\ubuntu-20.04.1-desktop-amd64.iso [fileSize]: 2,785,017,856 #.

4. Поиск файлов по времени последнего изменения

В этом примере используется File.find() для поиска файлов, содержащих время последнего изменения, равное или после вчерашнего дня.

package com.mkyong.io.api; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class FileFindExample3 < private static DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"); public static void main(String[] args) throws IOException < // find files, LastModifiedTime from yesterday and above Listresult = findByLastModifiedTime( Paths.get("C:\\test"), Instant.now().minus(1, ChronoUnit.DAYS)); for (Path p : result) < // formatting. BasicFileAttributes attrs = Files.readAttributes(p, BasicFileAttributes.class); FileTime time = attrs.lastModifiedTime(); LocalDateTime localDateTime = time.toInstant() .atZone(ZoneId.systemDefault()) .toLocalDateTime(); System.out.println(String.format("%-40s [%s]", p, localDateTime.format(DATE_FORMATTER))); >> public static List findByLastModifiedTime(Path path, Instant instant) throws IOException < Listresult; try (Stream pathStream = Files.find(path, Integer.MAX_VALUE, (p, basicFileAttributes) -> < if(Files.isDirectory(p) || !Files.isReadable(p))< return false; >FileTime fileTime = basicFileAttributes.lastModifiedTime(); // negative if less, positive if greater // 1 means fileTime equals or after the provided instant argument // -1 means fileTime before the provided instant argument int i = fileTime.toInstant().compareTo(instant); return i > 0; > )) < result = pathStream.collect(Collectors.toList()); >return result; > > 

Выходные образцы и предположим, что сегодня 02/12/2020

C:\test\a.txt [02/12/2020 13:01:20] C:\test\b.txt [01/12/2020 12:11:21] #.

Источник

Читайте также:  Absolute Links

How to Find a File in Directory in Java

Learn different ways to find a file in a given directory and sub-directories with Java. The given examples will find all files with specified file names if there are more than one files with the same name in the sub-directories.

1. Find File by Walking the Directories

The easiest and most straightforward way of finding all files in a directory or its subdirectories is walking all the files using Files.walk() method. This method traverses the directories in a depth-first manner, so files in the deep-most sub-directories are searched first.

We can optionally pass the depth of the sub-directory level to search if the directory structure is too much nested and we do not wish to go that much deeper. Note that when we close the Stream, the directory is also closed.

String fileNameToFind = "test.txt"; File rootDirectory = new File("c:/temp"); final List foundFiles = new ArrayList<>(); try (Stream walkStream = Files.walk(rootDirectory.toPath())) < walkStream.filter(p ->p.toFile().isFile()) .forEach(f -> < if (f.toString().endsWith(fileNameToFind)) < foundFiles.add(f.toFile()); >>); >

If we want to iterate over 5 levels of sub-directories then we can use the following function:

try (Stream walkStream = Files.walk(rootDirectory.toPath(), 5))

If we want to stop the search after the first file is found then we can use the Stream.findFirst() method with the stream of paths.

Optional foundFile; try (Stream walkStream = Files.walk(rootDirectory.toPath())) < foundFile = walkStream.filter(p ->p.toFile().isFile()) .filter(p -> p.toString().endsWith(fileNameToFind)) .findFirst(); > if(foundFile.isPresent()) < System.out.println(foundFile.get()); >else

Recursion is an old-fashioned way to iterate over all the files and sub-directories and apply custom logic for matching the file names. Still, we can use it if it fits our solution.

Читайте также:  Java проверка значения на null

The following method findFilesByName() recursively iterates over the files and subdirectories and add the matching files into the foundFilesList.

The recursive function first lists all the files using File.listFiles() method and then iterates over them. During iteration, it further calls the listFiles() for all child directories that it checks using the file.isDirectory() method.

After the recursion ends, we can check the files found in this list.

final List foundFilesList = new ArrayList<>(); findFilesByName(rootDirectory, fileNameToFind, foundFilesList); public static void findFilesByName(File rootDir, String filenameToSearch, List foundFilesList) < Collectionfiles = List.of(rootDir.listFiles()); for (Iterator iterator = files.iterator(); iterator.hasNext(); ) < File file = (File) iterator.next(); if (file.isDirectory()) < findFilesByName(file, filenameToSearch, foundFilesList); >else if(file.getName().equalsIgnoreCase(filenameToSearch)) < foundFilesList.add(file); >> > System.out.println(foundFilesList); //Prints the found files

This short Java tutorial taught us to find a file by name in a given directory and its sub-directories. We also learned to control the search up to a configured depth of sub-directories. We used the Stream reduction method findFirst() as well if we wanted to terminate the search after the first occurrence of a matching file.

Источник

Оцените статью