使用Files.walkFileTree遍歷目錄文件
java.nio.file.Files.walkFileTree是JDK7新增的靜態(tài)工具方法。
1.Files.walkFileTree的原理介紹
static Path walkFileTree(Path start, Set<FileVisitOption> options, int maxDepth, FileVisitor<? super Path> visitor) throws IOException; static Path walkFileTree(Path start, FileVisitor<? super Path> visitor) throws IOException;
參數(shù)列表:
java.nio.file.Path start遍歷的起始路徑Set<java.nio.file.FileVisitOption> options遍歷選項int maxDepth遍歷深度java.nio.file.FileVisitor<? super Path> visitor遍歷過程中的行為控制器
2.遍歷行為控制器FileVisitor
接口java.nio.file.FileVisitor包含四個方法,涉及到遍歷過程中的幾個重要的步驟節(jié)點。
一般實際中使用SimpleFileVisitor簡化操作。
public interface FileVisitor<T> {
FileVisitResult preVisitDirectory(T dir, BasicFileAttributes attrs)
throws IOException;
FileVisitResult visitFile(T file, BasicFileAttributes attrs)
throws IOException;
FileVisitResult visitFileFailed(T file, IOException exc)
throws IOException;
FileVisitResult postVisitDirectory(T dir, IOException exc)
throws IOException;
}preVisitDirectory訪問一個目錄,在進入之前調(diào)用。postVisitDirectory一個目錄的所有節(jié)點都被訪問后調(diào)用。遍歷時跳過同級目錄或有錯誤發(fā)生,Exception會傳遞給這個方法visitFile文件被訪問時被調(diào)用。該文件的文件屬性被傳遞給這個方法visitFileFailed當文件不能被訪問時,此方法被調(diào)用。Exception被傳遞給這個方法。
3.遍歷行為結(jié)果 FileVisitResult
public enum FileVisitResult {
CONTINUE,
TERMINATE,
SKIP_SUBTREE,
SKIP_SIBLINGS;
}CONTINUE繼續(xù)遍歷SKIP_SIBLINGS繼續(xù)遍歷,但忽略當前節(jié)點的所有兄弟節(jié)點直接返回上一層繼續(xù)遍歷SKIP_SUBTREE繼續(xù)遍歷,但是忽略子目錄,但是子文件還是會訪問TERMINATE終止遍歷
4.查找指定文件
使用java.nio.file.Path提供的startsWith、endsWith等方法,需要特別注意的是:匹配的是路徑節(jié)點的完整內(nèi)容,而不是字符串。
例如: /usr/web/bbf.jar
Path path = Paths.get("/usr/web/bbf.jar");
path.endsWith("bbf.jar"); ?// true
path.endsWith(".jar"); ? ? // false5.使用PathMatcher
@Test
public void visitFile2() throws IOException {
// 查找java和txt文件
String glob = "glob:**/*.{java,txt}";
String path = "D:\\work_java\\bbf\\CORE";
final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(glob);
Files.walkFileTree(Paths.get(path), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
if (pathMatcher.matches(file)) {
System.out.println(file);
}
return FileVisitResult.CONTINUE;
}
});
}getPathMatcher方法的參數(shù)語法:規(guī)則:模式,其中規(guī)則支持兩種模式glob和regex。
5.1全局規(guī)則glob
使用類似于正則表達式但語法更簡單的模式,匹配路徑的字符串。
glob:*.java匹配以java結(jié)尾的文件glob:.匹配包含’.'的文件glob:*.{java,class}匹配以java或class結(jié)尾的文件glob:foo.?匹配以foo開頭且一個字符擴展名的文件glob:/home//在unix平臺上匹配,例如/home/gus/data等glob:/home/**在unix平臺上匹配,例如/home/gus,/home/gus/dataglob:c:\\*在windows平臺上匹配,例如c:foo,c:bar,注意字符串轉(zhuǎn)義
5.1.1規(guī)則說明
*匹配零個或多個字符與名稱組件,不跨越目錄**匹配零個或多個字符與名稱組件,跨越目錄(含子目錄)?匹配一個字符的字符與名稱組件\轉(zhuǎn)義字符,例如{表示匹配左花括號[]匹配方括號表達式中的范圍,連字符(-)可指定范圍。例如[ABC]匹配"A"、“B"和"C”;[a-z]匹配從"a"到"z";[abce-g]匹配"a"、“b”、“c”、“e”、“f”、“g”;[!..]匹配范圍之外的字符與名稱組件,例如[!a-c]匹配除"a"、“b”、"c"之外的任意字符{}匹配組中的任意子模式,多個子模式用","分隔,不能嵌套。
5.2正則規(guī)則regex
使用java.util.regex.Pattern支持的正則表達式。
5.2.1示例
獲取指定擴展名的文件
以下測試用例,目的都是獲取指定目錄下的.properties和.html文件。
/**
* 遞歸遍歷,字符串判斷
*
* @throws IOException IO異常
*/
@Test
public void visitFile1() throws IOException {
String path = "D:\\work_java\\hty\\HTY_CORE";
Files.walkFileTree(Paths.get(path), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
String pathStr = file.toString();
if (pathStr.endsWith("properties") || pathStr.endsWith("html")) {
System.out.println(file);
}
return FileVisitResult.CONTINUE;
}
});
}
/**
* 遞歸遍歷,glob模式
*
* @throws IOException IO異常
*/
@Test
public void visitFile2() throws IOException {
String glob = "glob:**/*.{properties,html}";
String path = "D:\\work_java\\hty\\HTY_CORE";
final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(glob);
Files.walkFileTree(Paths.get(path), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
if (pathMatcher.matches(file)) {
System.out.println(file);
}
return FileVisitResult.CONTINUE;
}
});
}
/**
* 遞歸遍歷,正則模式
*
* @throws IOException IO異常
*/
@Test
public void visitFile3() throws IOException {
// (?i)忽略大小寫,(?:)標記該匹配組不應(yīng)被捕獲
String reg = "regex:.*\\.(?i)(?:properties|html)";
String path = "D:\\work_java\\hty\\HTY_CORE";
final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(reg);
Files.walkFileTree(Paths.get(path), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
if (pathMatcher.matches(file)) {
System.out.println(file);
}
return FileVisitResult.CONTINUE;
}
});
}6.查找指定文件
/**
* 查找指定文件
*
* @throws IOException IO異常
*/
@Test
public void visitFile() throws IOException {
String path = "D:\\work_java\\hty\\HTY_CORE\\src";
Files.walkFileTree(Paths.get(path), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
// 使用endsWith,必須是路徑中的一段,而不是幾個字符
if (file.endsWith("log.java")) {
System.out.println(file);
// 找到文件,終止操作
return FileVisitResult.TERMINATE;
}
return FileVisitResult.CONTINUE;
}
});
}7.遍歷單層目錄
使用DirectoryStream會獲取指定目錄下的目錄和文件??梢允褂胣ewDirectoryStream的第二個參數(shù)進行篩選,glob語法。
/**
* 遍歷單層目錄
*
* @throws IOException IO異常
*/
@Test
public void dir() throws IOException {
Path source = Paths.get("D:\\work_java\\hty\\HTY_CORE\\src\\main\\resources");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(source, "*.xml")) {
Iterator<Path> ite = stream.iterator();
while (ite.hasNext()) {
Path pp = ite.next();
System.out.println(pp.getFileName());
}
}
}8.復(fù)制文件到新目錄
/**
* 遞歸復(fù)制
*
* @throws IOException IO異常
*/
@Test
public void copyAll() throws IOException {
Path source = Paths.get("D:\\work_java\\hty\\HTY_CORE\\src");
Path target = Paths.get("D:\\temp\\core");
// 源文件夾非目錄
if (!Files.isDirectory(source)) {
throw new IllegalArgumentException("源文件夾錯誤");
}
// 源路徑的層級數(shù)
int sourcePart = source.getNameCount();
Files.walkFileTree(source, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
// 在目標文件夾中創(chuàng)建dir對應(yīng)的子文件夾
Path subDir;
if (dir.compareTo(source) == 0) {
subDir = target;
} else {
// 獲取相對原路徑的路徑名,然后組合到target上
subDir = target.resolve(dir.subpath(sourcePart, dir.getNameCount()));
}
Files.createDirectories(subDir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.copy(file, target.resolve(file.subpath(sourcePart, file.getNameCount())),
StandardCopyOption.REPLACE_EXISTING);
return FileVisitResult.CONTINUE;
}
});
System.out.println("復(fù)制完畢");
}9.文件和流的復(fù)制
/**
* 流復(fù)制到文件
*
* @throws IOException IO異常
*/
@Test
public void copy1() throws IOException {
Path source = Paths.get("D:\\work_java\\hty\\HTY_CORE\\src\\main\\resources\\ehcache.xml");
Path target = Paths.get("D:\\temp\\");
if (!Files.exists(target)) {
Files.createDirectories(target);
}
Path targetFile = target.resolve(source.getFileName());
try (InputStream fs = FileUtils.openInputStream(source.toFile())) {
Files.copy(fs, targetFile, StandardCopyOption.REPLACE_EXISTING);
}
}
/**
* 文件復(fù)制到流
*
* @throws IOException IO異常
*/
@Test
public void copy2() throws IOException {
Path source = Paths.get("D:\\work_java\\hty\\HTY_CORE\\src\\main\\resources\\ehcache.xml");
Path target = Paths.get("D:\\temp\\core");
Path targetFile = target.resolve(source.getFileName());
if (!Files.exists(target)) {
Files.createDirectories(target);
}
try (OutputStream fs = FileUtils.openOutputStream(targetFile.toFile());
OutputStream out = new BufferedOutputStream(fs)) {
Files.copy(source, out);
}
}
10.Path與File的轉(zhuǎn)換
/**
* Path與File的轉(zhuǎn)換
*/
@Test
public void testPath() {
File file = new File("D:\\work_java\\hty\\HTY_CORE");
System.out.println(file.toURI());//file:/D:/work_java/hty/HTY_CORE
System.out.println(file.getAbsolutePath());//D:\work_java\hty\HTY_CORE
System.out.println(file.getName());//HTY_CORE
System.out.println("-------");
//File轉(zhuǎn)換為Path
Path path = Paths.get(file.toURI());
System.out.println(path.toUri());//file:///D:/work_java/hty/HTY_CORE
System.out.println(path.toAbsolutePath());//D:\work_java\hty\HTY_CORE
System.out.println(path.getFileName());//HTY_CORE
System.out.println("-------");
//Path轉(zhuǎn)換為File
File f = path.toFile();
System.out.println(f.getAbsolutePath());//D:\work_java\hty\HTY_CORE
}以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Maven中<distributionManagement>的使用及說明
本文主要介紹了Maven中的SNAPSHOT和RELEASE倉庫的區(qū)別,以及如何在POM文件中配置和使用快照版本,快照版本可以實現(xiàn)實時更新,方便開發(fā)過程中的依賴管理,同時,本文還總結(jié)了Maven的一些常用命令及其作用2025-01-01
SpringBoot實現(xiàn)Excel讀取的實例教程
這篇文章主要給大家介紹了關(guān)于SpringBoot實現(xiàn)Excel讀取的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12
Java 實現(xiàn)協(xié)同過濾算法推薦算法的示例代碼
本文介紹了協(xié)同過濾算法的概念,包括基于用戶的協(xié)同過濾和基于物品的協(xié)同過濾,文章詳細解釋了數(shù)據(jù)準備、相似度計算以及如何在Java中實現(xiàn)這些算法,通過一個簡單的用戶-物品評分矩陣示例,展示了如何計算用戶和物品之間的相似度,并推薦未評分的物品,感興趣的朋友一起看看吧2025-02-02
如何使用SpringBootCondition更自由地定義條件化配置
這篇文章主要介紹了如何使用SpringBootCondition更自由地定義條件化配置,幫助大家更好的理解和學習使用springboot框架,感興趣的朋友可以了解下2021-04-04
Java應(yīng)用開源框架實現(xiàn)簡易web搜索引擎
本篇文章主要介紹了Java應(yīng)用開源框架實現(xiàn)簡易web搜索引擎,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11
Netty4之如何實現(xiàn)HTTP請求、響應(yīng)
這篇文章主要介紹了Netty4之如何實現(xiàn)HTTP請求、響應(yīng)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04

