Java find file recursive

Рекурсивный поиск файлов в каталогах на Java

Вот пример, чтобы показать вам, как искать файл с именем ” post.php ” из каталога ” /Пользователи/mkyong/веб-сайты ” и все его подкаталоги рекурсивно.

package com.mkyong; import java.io.File; import java.util.ArrayList; import java.util.List; public class FileSearch < private String fileNameToSearch; private Listresult = new ArrayList(); public String getFileNameToSearch() < return fileNameToSearch; >public void setFileNameToSearch(String fileNameToSearch) < this.fileNameToSearch = fileNameToSearch; >public List getResult() < return result; >public static void main(String[] args) < FileSearch fileSearch = new FileSearch(); //try different directory and filename :) fileSearch.searchDirectory(new File("/Users/mkyong/websites"), "post.php"); int count = fileSearch.getResult().size(); if(count ==0)< System.out.println("\nNo result found!"); >else < System.out.println("\nFound " + count + " result!\n"); for (String matched : fileSearch.getResult())< System.out.println("Found : " + matched); >> > public void searchDirectory(File directory, String fileNameToSearch) < setFileNameToSearch(fileNameToSearch); if (directory.isDirectory()) < search(directory); >else < System.out.println(directory.getAbsoluteFile() + " is not a directory!"); >> private void search(File file) < if (file.isDirectory()) < System.out.println("Searching directory . " + file.getAbsoluteFile()); //do you have permission to read this directory? if (file.canRead()) < for (File temp : file.listFiles()) < if (temp.isDirectory()) < search(temp); >else < if (getFileNameToSearch().equals(temp.getName().toLowerCase())) < result.add(temp.getAbsoluteFile().toString()); >> > > else < System.out.println(file.getAbsoluteFile() + "Permission Denied"); >> > > 
Searching directory . /Users/mkyong/websites Searching directory . /Users/mkyong/websites/wp-admin Searching directory . /Users/mkyong/websites/wp-admin/css Searching directory . /Users/mkyong/websites/wp-admin/images Searching directory . /Users/mkyong/websites/wp-admin/images/screenshots Searching directory . /Users/mkyong/websites/wp-admin/includes Searching directory . /Users/mkyong/websites/wp-admin/js Searching directory . /Users/mkyong/websites/wp-admin/maint Searching directory . /Users/mkyong/websites/wp-admin/network Searching directory . /Users/mkyong/websites/wp-admin/user Searching directory . /Users/mkyong/websites/wp-content Searching directory . /Users/mkyong/websites/wp-content/plugins //long list, omitted. Found 3 result! Found : /Users/mkyong/websites/wp-admin/includes/post.php Found : /Users/mkyong/websites/wp-admin/post.php Found : /Users/mkyong/websites/wp-includes/post.php

Источник

How to find a file recursively in Java

In this tutorial we are going to learn about finding a file recursively in Java.

Читайте также:  Xpath with namespaces in java

using Java 8 we can locate a file in Java that is indicated by a starting path. It should search through a tree for a specified file. If the file is found, the location of the file should be returned.

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 BehindJava  public static void main(String[] args)  try (StreamPath> walkStream = Files.walk(Paths.get("C:\\Users\\cldee\\Downloads\\Programs")))  walkStream.filter(p -> p.toFile().isFile()).forEach(f ->  if (f.toString().endsWith(".exe"))  System.out.println(f + " found!"); > >); > catch (IOException e)  e.printStackTrace(); > > >
C:\Users\cldee\Downloads\Programs\GrammarlyInstaller.ckzgJs7dcmbh6ihhlnaq0102.exe found! C:\Users\cldee\Downloads\Programs\KMP64_2021.05.26.23.exe found! C:\Users\cldee\Downloads\Programs\npp.8.1.9.1.Installer.exe found! C:\Users\cldee\Downloads\Programs\picasa-3-9-138-150-multi-win.exe found! C:\Users\cldee\Downloads\Programs\Teams_windows_x64.exe found! C:\Users\cldee\Downloads\Programs\vlc-3.0.14-win64.exe found!

Источник

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.

Источник

Поиск каталогов рекурсивно для файла в Java

Вот пример, который показывает, как рекурсивно искать файл с именем « post.php » из каталога « /Users/example/websites » и всех его подкаталогов.

package com.example; import java.io.File; import java.util.ArrayList; import java.util.List; public class FileSearch < private String fileNameToSearch; private Listresult = new ArrayList(); public String getFileNameToSearch() < return fileNameToSearch; >public void setFileNameToSearch(String fileNameToSearch) < this.fileNameToSearch = fileNameToSearch; >public List getResult() < return result; >public static void main(String[] args) < FileSearch fileSearch = new FileSearch(); //try different directory and filename :) fileSearch.searchDirectory(new File("/Users/example/websites"), "post.php"); int count = fileSearch.getResult().size(); if(count ==0)< System.out.println("\nNo result found!"); >else < System.out.println("\nFound " + count + " result!\n"); for (String matched : fileSearch.getResult())< System.out.println("Found : " + matched); >> > public void searchDirectory(File directory, String fileNameToSearch) < setFileNameToSearch(fileNameToSearch); if (directory.isDirectory()) < search(directory); >else < System.out.println(directory.getAbsoluteFile() + " is not a directory!"); >> private void search(File file) < if (file.isDirectory()) < System.out.println("Searching directory . " + file.getAbsoluteFile()); //do you have permission to read this directory? if (file.canRead()) < for (File temp : file.listFiles()) < if (temp.isDirectory()) < search(temp); >else < if (getFileNameToSearch().equals(temp.getName().toLowerCase())) < result.add(temp.getAbsoluteFile().toString()); >> > > else < System.out.println(file.getAbsoluteFile() + "Permission Denied"); >> > >
Searching directory . /Users/example/websites Searching directory . /Users/example/websites/wp-admin Searching directory . /Users/example/websites/wp-admin/css Searching directory . /Users/example/websites/wp-admin/images Searching directory . /Users/example/websites/wp-admin/images/screenshots Searching directory . /Users/example/websites/wp-admin/includes Searching directory . /Users/example/websites/wp-admin/js Searching directory . /Users/example/websites/wp-admin/maint Searching directory . /Users/example/websites/wp-admin/network Searching directory . /Users/example/websites/wp-admin/user Searching directory . /Users/example/websites/wp-content Searching directory . /Users/example/websites/wp-content/plugins //long list, omitted. Found 3 result! Found : /Users/example/websites/wp-admin/includes/post.php Found : /Users/example/websites/wp-admin/post.php Found : /Users/example/websites/wp-includes/post.php

Источник

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