java中如何使用Files.newBufferedWriter写入文件呢?
下文讲述java中使用Files.newBufferedWriter写文件的方法分享,如下所示:
newBufferedWriter方法语法: newBufferedWriter(filePath, StandardCharsets.UTF_8, StandardOpenOption.WRITE))例:
package com.java265; 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) throws Exception { Path logFile = Paths.get("D:/test/test.log"); if (Files.notExists(logFile)) { Files.createFile(logFile); } try (BufferedWriter writer = Files.newBufferedWriter(logFile, StandardCharsets.UTF_8, StandardOpenOption.WRITE)) { for (int i = 0; i <8; i++) { writer.write(String.format("Message %s%n", i)); } } catch (Exception e) { e.printStackTrace(); } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。