在 Java 7 中使用 Files.newBufferedWriter 创建新文件或覆盖现有文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20291673/
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
Create new file or overwrite existing one with Files.newBufferedWriter in Java 7
提问by diminuta
I am giving a try to the new Files.newBufferedWriter in Java 7 and I can't get an example to work: I want to create a new file if it doesn't exist or overwrite it if it does.
我正在尝试 Java 7 中的新 Files.newBufferedWriter,但我无法得到一个工作示例:如果它不存在,我想创建一个新文件,或者如果它存在则覆盖它。
What I do is:
我要做的是:
OpenOption[] options = {StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING};
BufferedWriter writer = Files.newBufferedWriter(Paths.get("example.txt"), StandardCharsets.UTF_8, options);
I tried also with different options, but I can't get it to work.
我也尝试了不同的选项,但我无法让它工作。
Help?
帮助?
采纳答案by Sage
The documentation of this functionalready says us that:
newBufferedWriter(Path path, Charset cs, OpenOption... options)
newBufferedWriter(Path path, Charset cs, OpenOption... options)
The options parameter specifies how the the file is created or opened. If no options are presentthen this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE
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 of 0 if it exists.
options 参数指定文件的创建或打开方式。如果不存在选项,则此方法就像CREATE, TRUNCATE_EXISTING, and WRITE
存在选项一样工作。换句话说,它打开文件进行写入,如果文件不存在则创建文件,或者如果存在则最初将现有的常规文件截断为 0 大小。
So you could just do without passing an option:
所以你可以不传递选项:
BufferedWriter writer = Files.newBufferedWriter(Paths.get("example.txt"),
StandardCharsets.UTF_8);