我尝试文件编写如下:
String content = "Test File Content";
Files.write(path, content.getBytes(), StandardOpenOption.CREATE);
如果file不是create,则创建文件并写入内容。但如果文件可用,文件内容是Test File ContentTest File Content
,如果代码运行重复,文件内容是Test File ContentTest File ContentTest File Content
...
Files.write(path, content.getBytes(), StandardOpenOption.CREATE_NEW);
,如果file不是create,则创建file,然后抛出异常,如下所示:
java.nio.file.FileAlreadyExistsException:/ home / gyhot / Projects / indexing / ivt_new / target / test-classes / test_file at sun.nio.fs.UnixException.translateToIOException(UnixException.java:88)at ...
如何通过java新I / O覆盖文件?
你想在没有任何OpenOption
参数的情况下调用该方法。
Files.write(path, content.getBytes());
来自Javadoc:
options参数指定如何创建或打开文件。如果没有选项,则此方法的工作方式就像存在CREATE,TRUNCATE_EXISTING和WRITE选项一样。换句话说,它打开文件进行写入,如果文件不存在则创建文件,或者最初将现有常规文件截断为0
您想同时使用StandardOpenOption.TRUNCATE_EXISTING和StandardOpenOption.CREATE选项:
Files.write(path, content.getBytes(),
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING );