如何通过java nio writer覆盖文件?

cgu*_*zel 42 java io nio java-io

我尝试文件编写如下:

String content = "Test File Content";
Run Code Online (Sandbox Code Playgroud)
  • 我用过像: 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,则创建文件,而不是如下所示:

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覆盖文件?

Ram*_*oza 66

您想要在没有任何OpenOption参数的情况下调用该方法.

Files.write(path, content.getBytes());
Run Code Online (Sandbox Code Playgroud)

来自Javadoc:

options参数指定如何创建或打开文件.如果没有选项,则此方法的工作方式就像存在CREATE,TRUNCATE_EXISTING和WRITE选项一样.换句话说,它打开了书面文件,创建该文件,如果它不存在,或最初截断现有的常规文件的大小为0


rol*_*lfl 41

您想要同时使用StandardOpenOption.TRUNCATE_EXISTING和StandardOpenOption.CREATE选项:

Files.write(path, content.getBytes(),
         StandardOpenOption.CREATE,
         StandardOpenOption.TRUNCATE_EXISTING );
Run Code Online (Sandbox Code Playgroud)