首先我们来看看Path类:
package com.freesoft.java7newfeature;
import java.io.IOException;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
public class TestPath {
public static void main(String[] args) throws IOException {
Path path = Paths.get("test.txt");
// 赋值的文件名,带路径
System.out.println(path);
// 得到文件名,不带路径
System.out.println(path.getFileName());
// 得到目录及文件名数目
System.out.println(path.getNameCount());
// 得到不带路径的文件名
System.out.println(path.getName(path.getNameCount() - 1));
// 得到真实路径
Path realPath = path.toRealPath(LinkOption.NOFOLLOW_LINKS);
System.out.println(realPath);
}
}
Path类还有:
- getFileSystem() ,可以获取文件系统信息;
- register(WatchService watcher, WatchEvent.Kind<?>... events) ,可以得到对文件或目录的监听;
等操作;
接下来我们看看文件的拷贝、删除、移动及目录的创建操作,其余操作基本也都差不多,可以去查看帮助文件。
package com.freesoft.java7newfeature;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class TestFileAndDirectory {
public static void main(String[] args) throws IOException {
Path source = Paths.get("files/loremipsum.txt");
System.out.println(source.getFileName());
Path target = Paths.get("files/backup.txt");
// 拷贝文件,注意拷贝参数(如果存在,替换目标文件)
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
// Path toDel = Paths.get("files/backup.txt");
// Files.delete(toDel);
// System.out.println("File deleted.");
Path newDir = Paths.get("files/newdir");
Files.createDirectories(newDir);
Files.move(source, newDir.resolve(source.getFileName()), StandardCopyOption.REPLACE_EXISTING);
}
}
关于文本文件的读写操作可以参见下面的例子:
package com.freesoft.java7newfeature;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
public class TestReadingAndWritingTextFile {
public static void main(String[] args) {
Path source = Paths.get("files/loremipsum.txt");
Path target = Paths.get("files/backup.txt");
ArrayList<String> lines = new ArrayList<>();
// 设置文件的编码格式
Charset charset = Charset.forName("US-ASCII");
// 读文件
try (BufferedReader reader = Files.newBufferedReader(source, charset);){
String line = null;
while((line = reader.readLine()) != null) {
lines.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
// 写文件
try (BufferedWriter writer = Files.newBufferedWriter(target, charset)){
for (String line : lines) {
writer.append(line);
writer.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
我们看看Java 7中如何遍历文件和文件夹在,主要使用到了Files.walkFileTree()方法,传入的是一个SimpleFileVisitor<Path>参数:
Visitor类的实现代码:
package com.freesoft.testentity;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
public class MyFileVisitor extends SimpleFileVisitor<Path> {
// FileVisitor中的四个方法会返回一个FileVisitorResult,它代是一个枚举类,代表访问之后的行为。
// FileVisitor定义了如下几种行为:
// CONTINUE:代表访问之后的继续行为
// SKIP_SIBLINGS:代表继续访问,但不访问该文件或目录的兄弟文件或目录
// SKIP_SUBTREE:继续访问,但不访问该目录或文件的子目录
// TERMINATE:终止访问
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exec)
throws IOException {
// 访问文件夹之前调用
System.out.println("Just visited " + dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
// 访问文件夹之后调用
System.out.println("About to visit " + dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
// 访问文件后调用
if (attrs.isRegularFile())
System.out.print("Regular File:");
System.out.println(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc)
throws IOException {
// 文件不可访问时调用
System.out.println(exc.getMessage());
return FileVisitResult.CONTINUE;
}
}
测试代码:
package com.freesoft.java7newfeature;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.freesoft.testentity.MyFileVisitor;
public class TestFileTree {
public static void main(String[] args) throws IOException {
Path fileDir = Paths.get("files");
MyFileVisitor visitor = new MyFileVisitor();
Files.walkFileTree(fileDir, visitor);
}
}
ok,我们现在综合之前讲的内容来看看如何实现一个查找文件的程序。首先我们需要实现一个用来查找的类,我们使用visitor来实现:
package com.freesoft.testentity;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
public class FindFileVisitor extends SimpleFileVisitor<Path> {
private PathMatcher matcher = null;
private ArrayList<Path> list = new ArrayList<>();
public FindFileVisitor(String pattern) {
super();
// 这里需要匹配文件名,所以我们使用glob:
matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
// 如果需要使用正则表达式可以使用下面的
// matcher = FileSystems.getDefault().getPathMatcher("regex:" + pattern);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
Path name = file.getFileName();
System.out.println("Examing: " + name);
if (matcher.matches(name)) {
list.add(file);
}
return FileVisitResult.CONTINUE;
}
public ArrayList<Path> getList() {
return list;
}
}
之后我们的测试程序是这样的:
package com.freesoft.java7newfeature;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.freesoft.testentity.FindFileVisitor;
public class TestFindFile {
public static void main(String[] args) throws IOException {
Path path = Paths.get("files");
FindFileVisitor visitor = new FindFileVisitor("test*.txt");
Files.walkFileTree(path, visitor);
for (Path file : visitor.getList()) {
// 输出绝对路径
System.out.println(file.toRealPath(LinkOption.NOFOLLOW_LINKS));
}
}
}
最后我们看一下如何实现对目录下文件内容修改的监听,我们先看代码:
package com.freesoft.java7newfeature;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class TestFileListener {
public static void main(String[] args) {
// 创建一个监听服务
try (WatchService service = FileSystems.getDefault().newWatchService()){
// 设置路径
Path path = Paths.get("files");
// 注册监听器
path.register(service, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey watchKey;
do {
// 得到一个watch key
watchKey = service.take();
for (WatchEvent<?> event: watchKey.pollEvents()) {
// 如果事件列表不为空,打印事件内容
WatchEvent.Kind<?> kind = event.kind();
Path eventPath = (Path)event.context();
System.out.println(eventPath + ": " + kind + " : " + eventPath);
}
} while (watchKey.reset());
} catch (Exception e) {
e.printStackTrace();
}
}
}
接下来我们理清一下思路。对于目录下的文件操作需要做如下工作:
- 通过FileSystems.getDefault().newWatchService()创建一个监听服务;
- 设置路径;
- 对目录注册一个监听器;
- 之后进入循环,等待watch key;
- 此时如果有事件发生可通过watchkey的pollevent()方法获取;
- 之后可以对event处理;