Java 多种方式创建文件
本文我们学习如何创建文件,首先是jdk6,然后是jdk7的nio2,最后使用第三方库实现。
使用jdk6
首先我们使用JDK6的文件api实现:
@Test
public void givenUsingJDK6_whenCreatingFile_thenCorrect() throws IOException {
File newFile = new File("src/test/resources/newFile_jdk6.txt");
boolean success = newFile.createNewFile();
assertTrue(success);
}
需要注意的是,这种操作文件必须不存在才能成功;否则createNewFile操作会返回false。
使用jdk7
现在看看JDK7提供新的解决方案:
@Test
public void givenUsingJDK7nio2_whenCreatingFile_thenCorrect()
throws IOException {
Path newFilePath = Paths.get("src/test/resources/newFile_jdk7.txt");
Files.createFile(newFilePath);
}
代码非常简单,使用了Path代替原来的File。需要注意的是,新的API很好地利用了异常——如果文件已经存在,我们不再需要检查返回代码——我们得到的是FileAlreadyExistsException:
java.nio.file.FileAlreadyExistsException: srctestresourcesnewFile_jdk7.txt
at sun.n.f.WindowsException.translateToIOException(WindowsException.java:81)
使用 Guava
Guava方法只需一行代码:
@Test
public void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException {
Files.touch(new File("src/test/resources/newFile_guava.txt"));
}
使用Apache Commons IO 库
Apache Commons 提供了FileUtils.touch方法,实现与linux中“touch”相同的功能————创建新空文件,或者如果文件已经存在,其打开并关闭文件,不修改器内容但会更新文件的修改日期。如果没有权限修改,则会抛出IOException。同时如果文件的父目录不存在,其会自动创建。
@Test
public void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException {
FileUtils.touch(new File("src/test/resources/newFile_commonsio.txt"));
}
总结
我们学习了4种方式创建文件。