给定一个 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);
}
或者甚至更好,正如 Jon 在下面指出的那样:
Files.write(Paths.get(tmpFile), buffer);
关于java - 将字节数组写入 UTF8 编码的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30345688/