Ale*_*ber 3 java utf-8 java-io
给定 UTF-8 编码的字节数组(作为String 的 Base64 解码的结果)-将其写入 UTF-8 编码的文件的正确方法是什么?
下面的源代码(逐字节写入数组)正确吗?
OutputStreamWriter osw = new OutputStreamWriter(
new FileOutputStream(tmpFile), Charset.forName("UTF-8"));
for (byte b: buffer)
osw.write(b);
osw.close();
Run Code Online (Sandbox Code Playgroud)
不要使用Writer. 只需使用OutputStream. 使用 try-with-resource 的完整解决方案如下所示:
try (FileOutputStream fos = new FileOutputStream(tmpFile)) {
fos.write(buffer);
}
Run Code Online (Sandbox Code Playgroud)
或者甚至更好,正如乔恩在下面指出的那样:
Files.write(Paths.get(tmpFile), buffer);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13428 次 |
| 最近记录: |