摒弃File及InputStream那一套API。
内存中二进制数据拷贝使用common-io的IoUtils类;内存-文件系统交互使用Java7中的Files以及Paths类。
public class FileTest {
private static final String fullPath = "/Users/miracle/Desktop/a/my.txt";
@Test
public void path() {
// 生成path
Path path = Paths.get(fullPath);
// path及file互转
File file = path.toFile();
Path newPath = file.toPath();
Assert.assertEquals(path, newPath);
// 相对路径
Path path1 = Paths.get("/Users/miracle/Desktop", "a/my.txt");
Assert.assertEquals(path, path1);
}
@Test
public void create() throws IOException {
// 创建文件
Path path = Paths.get(fullPath);
if (!Files.exists(path)) {
// 需要先保证父目录是存在的,其实这里使用apache的FileUtils.touch(path.toFile())方法更方便,会自动创建缺失目录
Files.createDirectories(path.getParent());
Files.createFile(path);
}
}
@Test
public void write() throws IOException {
Path path = Paths.get(fullPath);
for(int i = 0; i < 10; i++) {
String line = "line " + i + "content\n";
Files.write(path, line.getBytes(), StandardOpenOption.APPEND);
}
}
@Test
public void read() throws IOException {
// 逐行读取文件
Path path = Paths.get(fullPath);
Files.lines(path).forEach(System.out::println);
}
@Test
public void list() throws IOException {
// 仅遍历一级目
Path path = Paths.get(fullPath).getParent();
Files.list(path).forEach(System.out::println);
}
@Test
public void walk() throws IOException {
// 可以指定遍历层次
Path path = Paths.get("/Users/miracle/Desktop");
Files.walk(path).forEach(System.out::println);
}
}