Java8新特性一点通 | 回顾文件操作和watchService文件变更监视操作
文件操作
今天重温了一些文件操作:
- Files.list()
遍历文件和目录
//List all files and sub-directories using Files.list()
try {
Files.list(Paths.get(".")).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
Files.newDirectoryStream()
遍历文件和目录
//List files and sub-directories with Files.newDirectoryStream()
try {
Files.newDirectoryStream(Paths.get(".")).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
Files::isReularFile
找出目录中的文件
//List only files inside directory using filter expression
try {
Files.list(Paths.get(".")).filter(Files::isRegularFile).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
file->file.isHidden()
找出隐藏文件
//Find all hidden files in directory
final File[] files = new File(".").listFiles(file->file.isHidden());
for(File file:files){
System.out.println(file.getName());
}
Files.newBufferedWriter
迅速创建一个BufferedWriter,可以使编码语法更简洁
//Write to file using BufferedWriter
Path path = Paths.get("D:\\test.txt");
try(BufferedWriter writer = Files.newBufferedWriter(path)){
writer.write("Hello World!");
} catch (IOException e) {
e.printStackTrace();
}
Files.write()
使用简介的语法写入内容到文件
//Write to file using Files.write()
try {
Files.write(Paths.get("D:\\test1.txt"),"Hello".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
Tips:
对于比较大文件夹,使用DirectoryStream
会性能更好
WatchService
利用WatchService
对文件目录进行监视,可以对目录中增删改查这些动作进行监控
public class WatchServiceExample2 {
public static void main(String[] args) throws IOException {
Path curPath = Paths.get(".");
WatchService watchService = curPath.getFileSystem().newWatchService();
//遍历并注册目录
walkAndRegisterDirectories(curPath, watchService);
try {
//监听目录变化
while (true) {
WatchKey watchKey = watchService.take();
for (WatchEvent event : watchKey.pollEvents()) {
System.out.println(event.kind());
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void walkAndRegisterDirectories(Path path, WatchService watchService) throws IOException {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
registerDirectory(dir, watchService);
return FileVisitResult.CONTINUE;
}
});
}
private static void registerDirectory(Path dir, WatchService watchService) throws IOException {
WatchKey key = dir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE
, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
}
}
Evan Leung,CSDN博客砖家,ACP认证砖家,在IT行业摸滚打爬多年,经历了金融行业和移动互联网行业,参与多个大中型企业级项目设计与核心开发,曾在某一线互联网金融公司担任产品线高级技术经理,目前在某世界500强金融公司打杂。