




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
第使用Files.walkFileTree遍歷目錄文件目錄1.Files.walkFileTree的原理介紹2.遍歷行為控制器FileVisitor3.遍歷行為結果FileVisitResult4.查找指定文件5.使用PathMatcher5.1全局規則glob5.2正則規則regex6.查找指定文件7.遍歷單層目錄8.復制文件到新目錄9.文件和流的復制10.Path與File的轉換java.nio.file.Files.walkFileTree是JDK7新增的靜態工具方法。
1.Files.walkFileTree的原理介紹
staticPathwalkFileTree(Pathstart,SetFileVisitOptionoptions,intmaxDepth,FileVisitorsuperPathvisitor)throwsIOException;
staticPathwalkFileTree(Pathstart,FileVisitorsuperPathvisitor)throwsIOException;
參數列表:
java.nio.file.Pathstart遍歷的起始路徑Setjava.nio.file.FileVisitOptionoptions遍歷選項intmaxDepth遍歷深度java.nio.file.FileVisitorsuperPathvisitor遍歷過程中的行為控制器
2.遍歷行為控制器FileVisitor
接口java.nio.file.FileVisitor包含四個方法,涉及到遍歷過程中的幾個重要的步驟節點。
一般實際中使用SimpleFileVisitor簡化操作。
publicinterfaceFileVisitorT{
FileVisitResultpreVisitDirectory(Tdir,BasicFileAttributesattrs)
throwsIOException;
FileVisitResultvisitFile(Tfile,BasicFileAttributesattrs)
throwsIOException;
FileVisitResultvisitFileFailed(Tfile,IOExceptionexc)
throwsIOException;
FileVisitResultpostVisitDirectory(Tdir,IOExceptionexc)
throwsIOException;
}
preVisitDirectory訪問一個目錄,在進入之前調用。postVisitDirectory一個目錄的所有節點都被訪問后調用。遍歷時跳過同級目錄或有錯誤發生,Exception會傳遞給這個方法visitFile文件被訪問時被調用。該文件的文件屬性被傳遞給這個方法visitFileFailed當文件不能被訪問時,此方法被調用。Exception被傳遞給這個方法。
3.遍歷行為結果FileVisitResult
publicenumFileVisitResult{
CONTINUE,
TERMINATE,
SKIP_SUBTREE,
SKIP_SIBLINGS;
}
CONTINUE繼續遍歷SKIP_SIBLINGS繼續遍歷,但忽略當前節點的所有兄弟節點直接返回上一層繼續遍歷SKIP_SUBTREE繼續遍歷,但是忽略子目錄,但是子文件還是會訪問TERMINATE終止遍歷
4.查找指定文件
使用java.nio.file.Path提供的startsWith、endsWith等方法,需要特別注意的是:匹配的是路徑節點的完整內容,而不是字符串。
例如:/usr/web/bbf.jar
Pathpath=Paths.get("/usr/web/bbf.jar");
path.endsWith("bbf.jar");
//true
path.endsWith(".jar");
//false
5.使用PathMatcher
@Test
publicvoidvisitFile2()throwsIOException{
//查找java和txt文件
Stringglob="glob:**/*.{java,txt}";
Stringpath="D:\\work_java\\bbf\\CORE";
finalPathMatcherpathMatcher=FileSystems.getDefault().getPathMatcher(glob);
Files.walkFileTree(Paths.get(path),newSimpleFileVisitorPath(){
@Override
publicFileVisitResultvisitFile(Pathfile,BasicFileAttributesattrs)
throwsIOException{
if(pathMatcher.matches(file)){
System.out.println(file);
returnFileVisitResult.CONTINUE;
}
getPathMatcher方法的參數語法:規則:模式,其中規則支持兩種模式glob和regex。
5.1全局規則glob
使用類似于正則表達式但語法更簡單的模式,匹配路徑的字符串。
glob:*.java匹配以java結尾的文件glob:.匹配包含.的文件glob:*.{java,class}匹配以java或class結尾的文件glob:foo.匹配以foo開頭且一個字符擴展名的文件glob:/home//在unix平臺上匹配,例如/home/gus/data等glob:/home/**在unix平臺上匹配,例如/home/gus,/home/gus/dataglob:c:\\*在windows平臺上匹配,例如c:foo,c:bar,注意字符串轉義
5.1.1規則說明
*匹配零個或多個字符與名稱組件,不跨越目錄**匹配零個或多個字符與名稱組件,跨越目錄(含子目錄)匹配一個字符的字符與名稱組件\轉義字符,例如{表示匹配左花括號[]匹配方括號表達式中的范圍,連字符(-)可指定范圍。例如[ABC]匹配A、B和C;[a-z]匹配從a到z;[abce-g]匹配a、b、c、e、f、g;[!..]匹配范圍之外的字符與名稱組件,例如[!a-c]匹配除a、b、c之外的任意字符{}匹配組中的任意子模式,多個子模式用,分隔,不能嵌套。
5.2正則規則regex
使用java.util.regex.Pattern支持的正則表達式。
5.2.1示例
獲取指定擴展名的文件
以下測試用例,目的都是獲取指定目錄下的.properties和.html文件。
/**
*遞歸遍歷,字符串判斷
*@throwsIOExceptionIO異常
@Test
publicvoidvisitFile1()throwsIOException{
Stringpath="D:\\work_java\\hty\\HTY_CORE";
Files.walkFileTree(Paths.get(path),newSimpleFileVisitorPath(){
@Override
publicFileVisitResultvisitFile(Pathfile,BasicFileAttributesattrs)
throwsIOException{
StringpathStr=file.toString();
if(pathStr.endsWith("properties")||pathStr.endsWith("html")){
System.out.println(file);
returnFileVisitResult.CONTINUE;
*遞歸遍歷,glob模式
*@throwsIOExceptionIO異常
@Test
publicvoidvisitFile2()throwsIOException{
Stringglob="glob:**/*.{properties,html}";
Stringpath="D:\\work_java\\hty\\HTY_CORE";
finalPathMatcherpathMatcher=FileSystems.getDefault().getPathMatcher(glob);
Files.walkFileTree(Paths.get(path),newSimpleFileVisitorPath(){
@Override
publicFileVisitResultvisitFile(Pathfile,BasicFileAttributesattrs)
throwsIOException{
if(pathMatcher.matches(file)){
System.out.println(file);
returnFileVisitResult.CONTINUE;
*遞歸遍歷,正則模式
*@throwsIOExceptionIO異常
@Test
publicvoidvisitFile3()throwsIOException{
//(i)忽略大小寫,(:)標記該匹配組不應被捕獲
Stringreg="regex:.*\\.(i)(:properties|html)";
Stringpath="D:\\work_java\\hty\\HTY_CORE";
finalPathMatcherpathMatcher=FileSystems.getDefault().getPathMatcher(reg);
Files.walkFileTree(Paths.get(path),newSimpleFileVisitorPath(){
@Override
publicFileVisitResultvisitFile(Pathfile,BasicFileAttributesattrs)
throwsIOException{
if(pathMatcher.matches(file)){
System.out.println(file);
returnFileVisitResult.CONTINUE;
}
6.查找指定文件
/**
*查找指定文件
*@throwsIOExceptionIO異常
@Test
publicvoidvisitFile()throwsIOException{
Stringpath="D:\\work_java\\hty\\HTY_CORE\\src";
Files.walkFileTree(Paths.get(path),newSimpleFileVisitorPath(){
@Override
publicFileVisitResultvisitFile(Pathfile,BasicFileAttributesattrs)
throwsIOException{
//使用endsWith,必須是路徑中的一段,而不是幾個字符
if(file.endsWith("log.java")){
System.out.println(file);
//找到文件,終止操作
returnFileVisitResult.TERMINATE;
returnFileVisitResult.CONTINUE;
}
7.遍歷單層目錄
使用DirectoryStream會獲取指定目錄下的目錄和文件。可以使用newDirectoryStream的第二個參數進行篩選,glob語法。
/**
*遍歷單層目錄
*@throwsIOExceptionIO異常
@Test
publicvoiddir()throwsIOException{
Pathsource=Paths.get("D:\\work_java\\hty\\HTY_CORE\\src\\main\\resources");
try(DirectoryStreamPathstream=Files.newDirectoryStream(source,"*.xml")){
IteratorPathite=stream.iterator();
while(ite.hasNext()){
Pathpp=ite.next();
System.out.println(pp.getFileName());
}
8.復制文件到新目錄
/**
*遞歸復制
*@throwsIOExceptionIO異常
@Test
publicvoidcopyAll()throwsIOException{
Pathsource=Paths.get("D:\\work_java\\hty\\HTY_CORE\\src");
Pathtarget=Paths.get("D:\\temp\\core");
//源文件夾非目錄
if(!Files.isDirectory(source)){
thrownewIllegalArgumentException("源文件夾錯誤");
//源路徑的層級數
intsourcePart=source.getNameCount();
Files.walkFileTree(source,newSimpleFileVisitorPath(){
@Override
publicFileVisitResultpreVisitDirectory(Pathdir,BasicFileAttributesattrs)
throwsIOException{
//在目標文件夾中創建dir對應的子文件夾
PathsubDir;
if(pareTo(source)==0){
subDir=target;
}else{
//獲取相對原路徑的路徑名,然后組合到target上
subDir=target.resolve(dir.subpath(sourcePart,dir.getNameCount()));
Files.createDirectories(subDir);
returnFileVisitResult.CONTINUE;
@Override
publicFileVisitResultvisitFile(Pathfile,BasicFileAttributesattrs)throwsIOException{
Files.copy(file,target.resolve(file.subpath(sourcePart,file.getNameCount())),
StandardCopyOption.REPLACE_EXISTING);
returnFileVisitResult.CONTINUE;
System.out.println("復制完畢");
}
9.文件和流的復制
/**
*流復制到文件
*@throwsIOExceptionIO異常
@Test
publicvoidcopy1()throwsIOException{
Pathsource=Paths.get("D:\\work_java\\hty\\HTY_CORE\\src\\main\\resources\\ehcache.xml");
Pathtarget=Paths.get("D:\\temp\\");
if(!Files.exists(target)){
Files.createDirectories(target);
PathtargetFile=target.resolve(source.getFileName());
try(InputStreamfs=FileUtils.openInputStream(source.toFile())){
Files.copy(fs,targetFile,StandardCopyOption.REPLACE_EXISTING);
*文件復制到流
*@throwsIOExceptionIO異常
@Test
publicvoidcopy2()throwsIOException{
Pathsource=Paths.get("D:\\work_java\\hty\\HTY_CORE\\src\\main\\resources\\ehcache.xml");
Pathtarget=Paths.get("D:\\temp\\core");
PathtargetFile=target.resolve(source.getFileName());
if(!Files.exists(target)){
Files.createDirectories(target);
try(OutputStreamfs=FileUtils.openOutputStream(targetFile.toFile());
O
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年衛生資格考試藥物副作用試題及答案
- 2025年功能分析衛生資格考試試題及答案
- 公共設施維護管理補充協議
- 個性化撫養費稅務處理及支付協議
- 老齡教育機構運營權轉讓合同
- 2025年自考行政管理課程建筑試題及答案
- 文化概論中的管理知識試題及答案
- 藥師考試臨床決策支持的重要性試題及答案
- 影視作品音樂制作技術保密與版權授權合同
- 知識產權專利許可與技術培訓合作合同
- 萵筍育苗合同協議
- 2025年高考政治三輪沖刺復習:統編版選擇性必修3《邏輯與思維》開放類主觀題 提分刷題練習題(含答案)
- 電鍍車間廠房合同協議
- 森林火災后生態恢復的策略探討
- 2025-2030中國戰斗機行業市場發展趨勢與前景展望戰略研究報告
- 大學英語四級考試2024年12月真題(第一套)Part I Writing
- 吡侖帕奈產品簡介
- 高處作業力學基礎知識
- 洗煤廠應急救援預案
- 幼兒園科學發現室環境布置設計方案
- 《企業的績效管理問題與優化策略的分析案例-以舍得酒業公司為例9100字》
評論
0/150
提交評論