Java find file with path

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.

Читайте также:  Чему равно null javascript

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.

Источник

Java IO & NIO — Files.find() Examples

This method searches for files in a file tree rooted at a given starting file path. Parameters: start — the starting file maxDepth — the maximum number of directory levels to search matcher — the function used to decide whether a file should be included in the returned stream options — options to configure the traversal Returns: An instance of java.util.stream.Stream having matched paths (java.nio.file.Path).

Examples

c:\test

c:\test>tree c:\test /F /A
Folder PATH listing for volume OS_Install
Volume serial number is 7844-2D90
C:\TEST
\---f1
+---f2
| f2.txt
| items.txt
|
\---f3
| random-items.txt
|
\---f5
old-file.txt

package com.logicbig.example.files;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class FindExample
public static void main(String. args) throws IOException Path testPath = Paths.get("c:\\test");
//finding files containing 'items' in name
Stream stream =
Files.find(testPath, 100,
(path, basicFileAttributes) -> File file = path.toFile();
return !file.isDirectory() &&
file.getName().contains("items");
>);
stream.forEach(System.out::println);
>
>

Output

c:\test\f1\f2\items.txt
c:\test\f1\f3\random-items.txt

c:\test

c:\test>tree c:\test /F /A
Folder PATH listing for volume OS_Install
Volume serial number is 000000E6 7844:2D90
C:\TEST
\---f1
+---f2
| f2.txt
| items.txt
|
\---f3
| random-items.txt
|
\---f5
old-file.txt

package com.logicbig.example.files;

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.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.stream.Stream;

public class FindExample2
public static void main(String. args) throws IOException Path testPath = Paths.get("c:\\test");
LocalDateTime target = LocalDate.of(2016, 1, 1).atStartOfDay();
//finding files which were created before target date
Stream stream = Files.find(testPath, 100,
(path, basicFileAttributes) -> try LocalDateTime created = getCreationDateTime(basicFileAttributes);
return created.isBefore(target);
> catch (IOException e) e.printStackTrace();
>
return false;
>);

stream.forEach((p) -> System.out.println(p);
try BasicFileAttributes attr = Files.readAttributes(p,
BasicFileAttributes.class);
System.out.println("date created :" + getCreationDateTime(attr));
> catch (IOException e) e.printStackTrace();
>
>);
>

public static LocalDateTime getCreationDateTime(BasicFileAttributes attr)
throws IOException
return attr.creationTime()
.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
>
>

Output

c:\test\f1\f3\f5\old-file.txt
date created :2015-12-14T14:29

Источник

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