将字节数组写入 UTF8 编码的文件
Writing byte array to an UTF8-encoded file
给定一个 UTF-8 编码的字节数组(base64 decoding of a String 的结果)- 将其写入 UTF-8 编码文件的正确方法是什么?
下面的源码(逐字节写入数组)是否正确?
OutputStreamWriter osw = new OutputStreamWriter(
new FileOutputStream(tmpFile), Charset.forName("UTF-8"));
for (byte b: buffer)
osw.write(b);
osw.close();
不要使用 Writer
。只需使用 OutputStream
。使用 try-with-resource 的完整解决方案如下所示:
try (FileOutputStream fos = new FileOutputStream(tmpFile)) {
fos.write(buffer);
}
甚至更好,正如乔恩在下面指出的那样:
Files.write(Paths.get(tmpFile), buffer);
给定一个 UTF-8 编码的字节数组(base64 decoding of a String 的结果)- 将其写入 UTF-8 编码文件的正确方法是什么?
下面的源码(逐字节写入数组)是否正确?
OutputStreamWriter osw = new OutputStreamWriter(
new FileOutputStream(tmpFile), Charset.forName("UTF-8"));
for (byte b: buffer)
osw.write(b);
osw.close();
不要使用 Writer
。只需使用 OutputStream
。使用 try-with-resource 的完整解决方案如下所示:
try (FileOutputStream fos = new FileOutputStream(tmpFile)) {
fos.write(buffer);
}
甚至更好,正如乔恩在下面指出的那样:
Files.write(Paths.get(tmpFile), buffer);