下面给出的是一个 Java 示例,用于演示如何将“UTF-8”编码数据写入文件。
它在创建 OutputStreamWriter
时使用字符编码“UTF-8”。
import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.nio.charset.StandardCharsets; public class WriteUTF8Data { public static void main(String[] args) { try { File fileDir = new File("c:\temp\test.txt"); Writer out = new BufferedWriter(new OutputStreamWriter (new FileOutputStream(fileDir), StandardCharsets.UTF_8)); out.append("onitroad.com").append("\r\n"); out.append("UTF-8 Demo").append("\r\n"); out.append(" UTF8字符 测试 ").append("\r\n"); out.flush(); out.close(); } catch (UnsupportedEncodingException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } catch (Exception e) { System.out.println(e.getMessage()); } } }
在 Eclipse 中运行示例之前,我们需要在Eclipse IDE中启用 UTF-8 字符集支持。
默认情况下,它是禁用的。
日期:2020-09-17 00:09:29 来源:oir作者:oir