使用Files.walkFileTree遍历目录文件_第1页
使用Files.walkFileTree遍历目录文件_第2页
使用Files.walkFileTree遍历目录文件_第3页
使用Files.walkFileTree遍历目录文件_第4页
使用Files.walkFileTree遍历目录文件_第5页
已阅读5页,还剩6页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

第使用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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

最新文档

评论

0/150

提交评论