要打开要在JDK 7中写入的文件,可以使用Files.newBufferedWriter()方法。此方法带有三个参数。我们需要传递Path,,Charset和的varargs OpenOption。
例如,在下面的代码段中,我们传递了日志文件的路径,我们使用了StandardCharsets.UTF_8字符集,并使用StandardOpenOption.WRITE来打开一个文件进行写入。如果要打开文件并附加其内容而不是重写它,可以使用StandardOpenOption.APPEND。
package org.nhooo.example.io; import java.io.BufferedWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class FilesNewBufferedWriter { public static void main(String[] args) { Path logFile = Paths.get("app.log"); try (BufferedWriter writer = Files.newBufferedWriter(logFile, StandardCharsets.UTF_8, StandardOpenOption.WRITE)) { for (int i = 0; i < 10; i++) { writer.write(String.format("Message %s%n", i)); } } catch (Exception e) { e.printStackTrace(); } } }
因为我们使用,所以StandardOpenOption.WRITE必须确保要写入的文件存在。如果该文件不可用,则会出现类似的错误java.nio.file.NoSuchFileException。