Поиск файлов в папке с помощью Java
Что мне нужно сделать, если поиск в папке говорит C:\example
Затем мне нужно пройти каждый файл и проверить, совпадает ли он с несколькими начальными символами, поэтому если файлы начинаются
temp****.txt
tempONE.txt
tempTWO.txt
Итак, если файл начинается с temp и имеет расширение .txt, я хотел бы затем поместить это имя файла в File file = new File("C:/example/temp***.txt);
, чтобы затем прочитать его в файле, тогда цикл должен перейти к следующему файлу проверьте, соответствует ли он, как указано выше.
Ответы
Ответ 1
Вы хотите File.listFiles(FileNameFilter filter)
.
Это даст вам список файлов в каталоге, который вы хотите, чтобы соответствовать определенному фильтру.
Код будет выглядеть так:
// your directory
File f = new File("C:\\example");
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("temp") && name.endsWith("txt");
}
});
Ответ 2
Вы можете использовать FilenameFilter, например:
File dir = new File(directory);
File[] matches = dir.listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return name.startsWith("temp") && name.endsWith(".txt");
}
});
Ответ 3
Я знаю, это старый вопрос. Но только ради полноты, лямбда-версия.
File dir = new File(directory);
File[] files = dir.listFiles((dir1, name) -> name.startsWith("temp") && name.endsWith(".txt"));
Ответ 4
Посмотрите java.io.File.list()
и FilenameFilter
.
Ответ 5
Рассмотрим Apache Commons IO, у него есть класс FileUtils, у которого есть метод listFiles
который может быть очень полезен в вашем случае.
Ответ 6
Appaste commons IO различные
FilenameUtils.wildcardMatch
Смотрите Apache javadoc здесь. Он соответствует шаблону с именем файла. Таким образом, вы можете использовать этот метод для своих сравнений.
Ответ 7
Список файлов Json из вашего каталога.
import java.io.File;
import java.io.FilenameFilter;
public class ListOutFilesInDir {
public static void main(String[] args) throws Exception {
File[] fileList = getFileList("directory path");
for(File file : fileList) {
System.out.println(file.getName());
}
}
private static File[] getFileList(String dirPath) {
File dir = new File(dirPath);
File[] fileList = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
});
return fileList;
}
}
Ответ 8
Как сказал @Clarke, вы можете использовать java.io.FilenameFilter
для фильтрации файла по конкретному условию.
В качестве дополнения я хотел бы показать, как использовать java.io.FilenameFilter
для поиска файла в текущем каталоге и его подкаталоге.
Общие методы getTargetFiles и printFiles используются для поиска файлов и их печати.
public class SearchFiles {
//It used in dfs
private Map<String, Boolean> map = new HashMap<String, Boolean>();
private File root;
public SearchFiles(File root){
this.root = root;
}
/**
* List eligible files on current path
* @param directory
* The directory to be searched
* @return
* Eligible files
*/
private String[] getTargetFiles(File directory){
if(directory == null){
return null;
}
String[] files = directory.list(new FilenameFilter(){
@Override
public boolean accept(File dir, String name) {
// TODO Auto-generated method stub
return name.startsWith("Temp") && name.endsWith(".txt");
}
});
return files;
}
/**
* Print all eligible files
*/
private void printFiles(String[] targets){
for(String target: targets){
System.out.println(target);
}
}
}
Я продемонстрирую, как использовать рекурсивный, bfs и dfs, чтобы выполнить задание.
Рекурсивный
/**
* How many files in the parent directory and its subdirectory <br>
* depends on how many files in each subdirectory and their subdirectory
*/
private void recursive(File path){
printFiles(getTargetFiles(path));
for(File file: path.listFiles()){
if(file.isDirectory()){
recursive(file);
}
}
if(path.isDirectory()){
printFiles(getTargetFiles(path));
}
}
public static void main(String args[]){
SearchFiles searcher = new SearchFiles(new File("C:\\example"));
searcher.recursive(searcher.root);
}
Первый поиск по ширине:
/**
* Search the node neighbors firstly before moving to the next level neighbors
*/
private void bfs(){
if(root == null){
return;
}
Queue<File> queue = new LinkedList<File>();
queue.add(root);
while(!queue.isEmpty()){
File node = queue.remove();
printFiles(getTargetFiles(node));
File[] childs = node.listFiles(new FileFilter(){
@Override
public boolean accept(File pathname) {
// TODO Auto-generated method stub
if(pathname.isDirectory())
return true;
return false;
}
});
if(childs != null){
for(File child: childs){
queue.add(child);
}
}
}
}
public static void main(String args[]){
SearchFiles searcher = new SearchFiles(new File("C:\\example"));
searcher.bfs();
}
Глубина первого поиска:
/** * Искать как можно дальше вдоль каждой ветки перед возвратом */ private void dfs() {
if(root == null){
return;
}
Stack<File> stack = new Stack<File>();
stack.push(root);
map.put(root.getAbsolutePath(), true);
while(!stack.isEmpty()){
File node = stack.peek();
File child = getUnvisitedChild(node);
if(child != null){
stack.push(child);
printFiles(getTargetFiles(child));
map.put(child.getAbsolutePath(), true);
}else{
stack.pop();
}
}
}
/**
* Get unvisited node of the node
*
*/
private File getUnvisitedChild(File node){
File[] childs = node.listFiles(new FileFilter(){
@Override
public boolean accept(File pathname) {
// TODO Auto-generated method stub
if(pathname.isDirectory())
return true;
return false;
}
});
if(childs == null){
return null;
}
for(File child: childs){
if(map.containsKey(child.getAbsolutePath()) == false){
map.put(child.getAbsolutePath(), false);
}
if(map.get(child.getAbsolutePath()) == false){
return child;
}
}
return null;
}
public static void main(String args[]){
SearchFiles searcher = new SearchFiles(new File("C:\\example"));
searcher.dfs();
}
Ответ 9
Начиная с Java 1.8, вы можете использовать Files.list для получения потока:
Path findFile(Path targetDir, String fileName) throws IOException {
return Files.list(targetDir).filter( (p) -> {
if (Files.isRegularFile(p)) {
return p.getFileName().toString().equals(fileName);
} else {
return false;
}
}).findFirst().orElse(null);
}
Ответ 10
Чтобы уточнить этот ответ, Apache IO Utils может сэкономить вам время. Рассмотрим следующий пример, который будет рекурсивно искать файл с заданным именем:
File file = FileUtils.listFiles(new File("the/desired/root/path"),
new NameFileFilter("filename.ext"),
FileFilterUtils.trueFileFilter()
).iterator().next();
Увидеть:
Ответ 11
Вы указываете имя своего файла, путь к каталогу для поиска и позволяете ему выполнять работу.
private static String getPath(String drl, String whereIAm) {
File dir = new File(whereIAm); //StaticMethods.currentPath() + "\\src\\main\\resources\\" +
for(File e : dir.listFiles()) {
if(e.isFile() && e.getName().equals(drl)) {return e.getPath();}
if(e.isDirectory()) {
String idiot = getPath(drl, e.getPath());
if(idiot != null) {return idiot;}
}
}
return null;
}
Ответ 12
- Сличитель. найти и файлы. Методы ходьбы могут быть опцией для поиска файлов более гибким способом
- Строка. Формат объединяет регулярные выражения для создания ограничений поиска
- Файлы. isRegularFile проверяет, является ли путь не каталогом, символической ссылкой и т.д.
Использование:
//Searches file names (start with "temp" and extension ".txt")
//in the current directory and subdirectories recursively
Path initialPath = Paths.get(".");
PathUtils.searchRegularFilesStartsWith(initialPath, "temp", ".txt").
stream().forEach(System.out::println);
Источник:
public final class PathUtils {
private static final String startsWithRegex = "(?<![_ \\-\\p{L}\\d\\[\\]\\(\\) ])";
private static final String endsWithRegex = "(?=[\\.\\n])";
private static final String containsRegex = "%s(?:[^\\/\\\\]*(?=((?i)%s(?!.))))";
public static List<Path> searchRegularFilesStartsWith(final Path initialPath,
final String fileName, final String fileExt) throws IOException {
return searchRegularFiles(initialPath, startsWithRegex + fileName, fileExt);
}
public static List<Path> searchRegularFilesEndsWith(final Path initialPath,
final String fileName, final String fileExt) throws IOException {
return searchRegularFiles(initialPath, fileName + endsWithRegex, fileExt);
}
public static List<Path> searchRegularFilesAll(final Path initialPath) throws IOException {
return searchRegularFiles(initialPath, "", "");
}
public static List<Path> searchRegularFiles(final Path initialPath,
final String fileName, final String fileExt)
throws IOException {
final String regex = String.format(containsRegex, fileName, fileExt);
final Pattern pattern = Pattern.compile(regex);
try (Stream<Path> walk = Files.walk(initialPath.toRealPath())) {
return walk.filter(path -> Files.isRegularFile(path) &&
pattern.matcher(path.toString()).find())
.collect(Collectors.toList());
}
}
private PathUtils() {
}
}
Попробуйте запуски с регулярным выражением для \txt\temp\tempZERO0.txt:
(?<![_ \-\p{L}\d\[\]\(\) ])temp(?:[^\/\\]*(?=((?i)\.txt(?!.))))
Попробуйте конец с регулярным выражением для \txt\temp\ZERO0temp.txt:
temp(?=[\\.\\n])(?:[^\/\\]*(?=((?i)\.txt(?!.))))
Try содержит регулярное выражение для \txt\temp\tempZERO0tempZERO0temp.txt:
temp(?:[^\/\\]*(?=((?i)\.txt(?!.))))