在 java 中,使用 files.write 指定编码需要传入一个包含字符集参数的 openoption。具体做法是调用 standardopenoption.write 配合 standardcharsets.utf_8(或其他 charset)作为方法参数,这样写入的字节流就会按照指定的编码格式进行转换。

Files.write 如何指定 UTF-8 编码写入文件?
直接回答:通过向 Files.write 方法传递 StandardCharsets.UTF_8 作为第三个参数,并配合 StandardOpenOption.WRITE 选项,即可实现 UTF-8 编码的文件写入。

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
Path path = Path.of("test.txt");
List<String> lines = List.of("Hello", "World");
// 指定 UTF-8 编码和写入模式
Files.write(path, lines, StandardCharsets.UTF_8, StandardOpenOption.WRITE);
}
}
运行上述代码后,test.txt 文件将以 UTF-8 编码保存内容。如果文件已存在且未使用 APPEND 选项,原有内容会被覆盖。
立即学习“Java免费学习笔记(深入)”;
使用 Husky 将 pre-commit、pre-push 和 commit-msg 检查集成到仓库中,以便代理和开发人员在更改离开工作站之前运行相同的本地防护措施。
Files.write 支持哪些其他编码方式?
直接回答:Files.write 支持所有 java.nio.charset.Charset 定义的编码,如 GBK、ISO-8859-1 等,只需替换 StandardCharsets.UTF_8 为对应的常量或自定义 Charset 对象即可。

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
Path path = Path.of("test_gbk.txt");
List<String> lines = List.of("中文测试");
// 使用 GBK 编码
Charset gbk = Charset.forName("GBK");
Files.write(path, lines, gbk, StandardOpenOption.WRITE);
}
}
运行后,test_gbk.txt 将以 GBK 编码保存中文内容。注意:不同编码对多字节字符的支持不同,需确保目标环境能正确解析。
当使用 StandardOpenOption.APPEND 时,编码是否仍生效?
直接回答:是的,即使使用 APPEND 选项追加内容,指定的编码依然生效,新写入的内容会按该编码追加到文件末尾。
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
Path path = Path.of("test_append.txt");
List<String> lines = List.of("Appended Line");
// 追加模式 + UTF-8 编码
Files.write(path, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
}
}
此操作会在文件末尾追加 UTF-8 编码的新行,不影响原有内容的编码结构。

















