java glob paths_java遍历文件目录

本文介绍了一个Java程序,利用Glob模式在指定目录及其子目录下搜索匹配特定模式的文件。通过`Files.walkFileTree()`和`PathMatcher`,实现了根据如`**/*.{tar.gz,msi}`这样的Glob模式找到文件并返回其绝对路径的列表。Glob模式在Java SE7的NIO库中被引入,允许开发者用通配符进行文件查找,如`*`代表任意字符或字符串,`?`代表任意单个字符。" 125927887,14906196,ZenCart OpenzcTPL模板安装步骤详解,"['ZenCart模板', 'OpenzcTPL', '电商建站', 'PHP', '服务器配置']
摘要由CSDN通过智能技术生成

下面是一个Java程序,使用了Glob模式来搜索指定的目录及其子目录,返回符合匹配条件的文件绝对路径列表:

package cn.cloud.worker.utils;

import java.io.IOException;

import java.nio.file.FileSystems;

import java.nio.file.FileVisitResult;

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.PathMatcher;

import java.nio.file.Paths;

import java.nio.file.SimpleFileVisitor;

import java.nio.file.attribute.BasicFileAttributes;

import java.util.ArrayList;

import java.util.List;

/**

* @author YPF

*/

public class FileInfoUtil {

/**

* 使用glob模式匹配文件名,查找符合条件的文件列表

* @param location

* @param glob

* @return

* @throws IOException

*/

public static List findFileByGlob(String location, String glob) throws IOException {

final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(glob);

List fileList = new ArrayList<>();

Files.walkFileTree(Paths.get(location), new SimpleFileVisitor() {

@Override

public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) {

if (pathMatcher.matches(path)) {

fileList.add(path.toString());

}

return FileVisitResult.CONTINUE;

}

@Override

public FileVisitResult visitFileFailed(Path file, IOException exc) {

return FileVisitResult.CONTINUE;

}

});

return fileList;

}

public static void main(String args[]) throws IOException {

String glob = "glob:**/*.{tar.gz,msi}";

String path = "D:\\";

System.out.println(findFileByGlob(path, glob));

}

}

在编程设计中,Glob是一种模式,它使用通配符来指定文件名。例如:.java就是一个简单的Glob,它指定了所有扩展名为“java”的文件。Glob模式中广泛使用了两个通配符“”和“?”。其中星号表示“任意的字符或字符组成字符串”,而问号则表示“任意单个字符”。

Java SE7的NIO库中引入了Glob模式,它用于FileSystem类,在PathMatcher getPathMatcher(String syntaxAndPattern)方法中使用。Glob可以作为参数传递给PathMatcher。同样地,在Files类中也可以使用Glob来遍历整个目录。

下面是Java NIO中使用的Glob模式:

Glob模式及描述

*.{html,htm} 匹配所有扩展名为.html或.htm的文件。{ }用于组模式,它使用逗号分隔,逗号后不可以有空格

989794bd445e

https://blog.csdn.net/weixin_34396902/article/details/89582624

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值