JAVA正则表达式过滤文件的实现方法-创新互联
JAVA正则表达式过滤文件的实现方法

正则表达式过滤文件列表,听起来简单,如果用java实现,还真需要一番周折,本文简析2种方式
1、适用于路径确定,文件名时正则表达式的情况(jdk6的写法)
String filePattern = "/data/logs/.+\\.log";
File f = new File(filePattern);
File parentDir = f.getParentFile();
String regex = f.getName();
FileSystem FS = FileSystems.getDefault();
final PathMatcher matcher = FS.getPathMatcher("regex:" + regex);
DirectoryStream.Filter fileFilter = new DirectoryStream.Filter() {
@Override
public boolean accept(Path entry) throws IOException {
return matcher.matches(entry.getFileName()) && !Files.isDirectory(entry);
}
};
List result = Lists.newArrayList();
try (DirectoryStream stream = Files.newDirectoryStream(parentDir.toPath(), fileFilter)) {
for (Path entry : stream) {
result.add(entry.toFile());
}
} catch (IOException e) {
e.printStackTrace();
}
for(File file : result) {
System.out.println(file.getParent() + "/" + file.getName());
}
网站名称:JAVA正则表达式过滤文件的实现方法-创新互联
文章来源:http://www.jxjierui.cn/article/dijghg.html


咨询
建站咨询
