如何通过java nio writer覆盖文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19794101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to overwrite file via java nio writer?
提问by cguzel
I try files writer as follows:
我尝试文件编写器如下:
String content = "Test File Content";
- I used as like :
Files.write(path, content.getBytes(), StandardOpenOption.CREATE);
- 我用过:
Files.write(path, content.getBytes(), StandardOpenOption.CREATE);
If file is not create, file is created and content is written. But If file available , the file content is Test File ContentTest File Content
and if the code is run repeat, the file content is Test File ContentTest File ContentTest File Content
...
如果未创建文件,则创建文件并写入内容。但是如果文件可用,文件内容是Test File ContentTest File Content
,如果代码重复运行,文件内容是Test File ContentTest File ContentTest File Content
......
- I used as like :
Files.write(path, content.getBytes(), StandardOpenOption.CREATE_NEW);
,
- 我用过:
Files.write(path, content.getBytes(), StandardOpenOption.CREATE_NEW);
,
If file is not create, file is created and than thow an exception as follow:
如果没有创建文件,则创建文件,然后出现如下异常:
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.nio.file.FileAlreadyExistsException: /home/gyhot/Projects/indexing/ivt_new/target/test-classes/test_file at sun.nio.fs.UnixException.translateToIOException(UnixException.java:88) at ...
How to overwrite file via java new I/O?
如何通过java new I/O覆盖文件?
采纳答案by RamonBoza
You want to call the method without any OpenOption
arguments.
您想在没有任何OpenOption
参数的情况下调用该方法。
Files.write(path, content.getBytes());
From the Javadoc:
来自 Javadoc:
The options parameter specifies how the the file is created or opened. If no options are present then this method works as if the
CREATE
,TRUNCATE_EXISTING
, andWRITE
options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of0
options 参数指定文件的创建或打开方式。如果不存在任何选项,则此方法的工作原理就好像
CREATE
,TRUNCATE_EXISTING
和WRITE
选项都存在。换句话说,它打开文件进行写入,如果文件不存在则创建文件,或者最初将现有的常规文件截断为大小0
回答by rolfl
You want to use both StandardOpenOption.TRUNCATE_EXISTINGand StandardOpenOption.CREATE options together:
您想同时使用StandardOpenOption.TRUNCATE_EXISTING和 StandardOpenOption.CREATE 选项:
Files.write(path, content.getBytes(),
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING );