JDK1.7 NIO.2 读写遍历文件树
程序员文章站
2022-07-02 16:55:15
...
使用jdk7 nio.2遍历文件夹里所有文件
首先需要写FileHandler类,继承SimpleFileVisitor<Path>
根据需要重写SimpleFileVisitor里面的方法
比如,访问文件前做些什么,访问文件时做些什么,访问后做些什么
例子中的这行就是遍历每个文件时做的事情,打印一下文件的路径
System.out.println("Visiting:" + path);//do some thing
然后通过Files.walkFileTree遍历headDir这个目录下的所有文件
Files.walkFileTree(headDir, this);
完整的例子如下:
import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.Objects; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @Service("fileHandler") public class FileHandler extends SimpleFileVisitor<Path> { private static final Logger logger = LogManager.getLogger(FileHandler.class); public void handleMultipleFiles(String path) { Path headDir = Paths.get(path); try { Files.walkFileTree(headDir, this); } catch (IOException e) { logger.info("WalkFileTree Failed:", e); } } @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException { Objects.requireNonNull(path); Objects.requireNonNull(attrs); System.out.println("Visiting:" + path);//do some thing return FileVisitResult.CONTINUE; } }
测试类:
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = AppContext.class) public class TestVisit { @Autowired private FileHandler fileHandler; @Test public void test() { fileHandler.handleMultipleFiles("C:/Mapper"); } }
Spring注解的配置:AppContext.class
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; @Configuration @Profile(value = { "default" }) @ComponentScan(basePackages = "com.demo") public class AppContext { }
总结:
NIO.2读写文件和遍历文件树还是很方便的
除了读写,还有更高级的文件权限管理功能,文件修改的监控等功能等等
对文件的目录操作工具
import java.nio.file.Path;
import java.nio.file.Paths;
Path filePath = Paths.get("/test"); System.out.println(filePath); System.out.println(filePath.resolve("pretty.json")); System.out.println(filePath.resolveSibling("pretty2.json")); System.out.println(filePath.toAbsolutePath()); System.out.println(filePath.getParent());
对文件的操作工具
import java.nio.file.Files;
Files.readAllBytes(path); Files.write(path, bytes); Files.copy(source, target); Files.delete(path); Files.createDirectory(dir); Files.createFile(path); Files.walkFileTree(start, visitor);
以上