Java 多种方式创建文件

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种方式创建文件。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值