Find file in java project

Файлы 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] #.

Источник

Finding Files

If you have ever used a shell script, you have most likely used pattern matching to locate files. In fact, you have probably used it extensively. If you haven’t used it, pattern matching uses special characters to create a pattern and then file names can be compared against that pattern. For example, in most shell scripts, the asterisk, * , matches any number of characters. For example, the following command lists all the files in the current directory that end in .html :

The java.nio.file package provides programmatic support for this useful feature. Each file system implementation provides a PathMatcher . You can retrieve a file system’s PathMatcher by using the getPathMatcher(String) method in the FileSystem class. The following code snippet fetches the path matcher for the default file system:

String pattern = . ; PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);

The string argument passed to getPathMatcher specifies the syntax flavor and the pattern to be matched. This example specifies glob syntax. If you are unfamiliar with glob syntax, see What is a Glob.

Glob syntax is easy to use and flexible but, if you prefer, you can also use regular expressions, or regex, syntax. For further information about regex, see the Regular Expressions lesson. Some file system implementations might support other syntaxes.

If you want to use some other form of string-based pattern matching, you can create your own PathMatcher class. The examples in this page use glob syntax.

Once you have created your PathMatcher instance, you are ready to match files against it. The PathMatcher interface has a single method, matches , that takes a Path argument and returns a boolean: It either matches the pattern, or it does not. The following code snippet looks for files that end in .java or .class and prints those files to standard output:

PathMatcher matcher = FileSystems.getDefault().getPathMatcher(«glob:*.»); Path filename = . ; if (matcher.matches(filename))

Recursive Pattern Matching

Searching for files that match a particular pattern goes hand-in-hand with walking a file tree. How many times do you know a file is somewhere on the file system, but where? Or perhaps you need to find all files in a file tree that have a particular file extension.

The Find example does precisely that. Find is similar to the UNIX find utility, but has pared down functionally. You can extend this example to include other functionality. For example, the find utility supports the -prune flag to exclude an entire subtree from the search. You could implement that functionality by returning SKIP_SUBTREE in the preVisitDirectory method. To implement the -L option, which follows symbolic links, you could use the four-argument walkFileTree method and pass in the FOLLOW_LINKS enum (but make sure that you test for circular links in the visitFile method).

To run the Find application, use the following format:

The pattern is placed inside quotation marks so any wildcards are not interpreted by the shell. For example:

Here is the source code for the Find example:

/** * Sample code that finds files that match the specified glob pattern. * For more information on what constitutes a glob pattern, see * https://docs.oracle.com/javase/tutorial/essential/io/fileOps.html#glob * * The file or directories that match the pattern are printed to * standard out. The number of matches is also printed. * * When executing this application, you must put the glob pattern * in quotes, so the shell will not expand any wild cards: * java Find . -name "*.java" */ 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 < 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) < Path name = file.getFileName(); if (name != null && matcher.matches(name)) < numMatches++; System.out.println(file); >> // 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) < find(file); return CONTINUE; >// Invoke the pattern matching // method on each directory. @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) < 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 " + " -name \"\""); 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(); >>

Recursively walking a file tree is covered in Walking the File Tree.

Источник

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.

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.

Источник

Читайте также:  Ng bind html angularjs
Оцените статью