如何用java保存汉字到文件?

Fra*_*ank 10 java file character-encoding cjk

我使用以下代码将中文字符保存到.txt文件中,但是当我用Wordpad打开它时,我无法读取它.

StringBuffer Shanghai_StrBuf = new StringBuffer("\u4E0A\u6D77");
boolean Append = true;

FileOutputStream fos;
fos = new FileOutputStream(FileName, Append);
for (int i = 0;i < Shanghai_StrBuf.length(); i++) {
    fos.write(Shanghai_StrBuf.charAt(i));
}
fos.close();
Run Code Online (Sandbox Code Playgroud)

我能做什么 ?我知道如果我将中文字符剪切并粘贴到Wordpad中,我可以将其保存到.txt文件中.我如何用Java做到这一点?

McD*_*ell 10

这里有几个因素在起作用:

  • 文本文件没有用于描述其编码的内在元数据(对于所有关于角括号税的讨论,XML都很受欢迎)
  • Windows的默认编码仍然是8位(或双字节)" ANSI "字符集,其值范围有限 - 以此格式编写的文本文件不可移植
  • 为了告诉ANSI文件中的Unicode文件,Windows应用程序依赖于文件开头的字节顺序标记(严格来说不是这样--Raymond Chen解释).从理论上讲,BOM可以告诉您数据的字节顺序(字节顺序).对于UTF-8,即使只有一个字节顺序,Windows应用依赖于标记字节来自动确定它是Unicode(尽管您会注意到Notepad在其打开/保存对话框中有一个编码选项).
  • 说Java被破坏是错误的,因为它没有自动写入UTF-8 BOM.例如,在Unix系统上,将BOM写入脚本文件是错误的,并且许多Unix系统使用UTF-8作为其默认编码.有时候你不想在Windows上使用它,比如当你将数据附加到现有文件时:fos = new FileOutputStream(FileName,Append);

这是一种可靠地将UTF-8数据附加到文件的方法:

  private static void writeUtf8ToFile(File file, boolean append, String data)
      throws IOException {
    boolean skipBOM = append && file.isFile() && (file.length() > 0);
    Closer res = new Closer();
    try {
      OutputStream out = res.using(new FileOutputStream(file, append));
      Writer writer = res.using(new OutputStreamWriter(out, Charset
          .forName("UTF-8")));
      if (!skipBOM) {
        writer.write('\uFEFF');
      }
      writer.write(data);
    } finally {
      res.close();
    }
  }
Run Code Online (Sandbox Code Playgroud)

用法:

  public static void main(String[] args) throws IOException {
    String chinese = "\u4E0A\u6D77";
    boolean append = true;
    writeUtf8ToFile(new File("chinese.txt"), append, chinese);
  }
Run Code Online (Sandbox Code Playgroud)

注意:如果文件已经存在并且您选择追加并且现有数据不是 UTF-8编码的,那么代码将创建的唯一内容就是混乱.

以下是Closer此代码中使用的类型:

public class Closer implements Closeable {
  private Closeable closeable;

  public <T extends Closeable> T using(T t) {
    closeable = t;
    return t;
  }

  @Override public void close() throws IOException {
    if (closeable != null) {
      closeable.close();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

此代码使Windows风格最佳猜测如何基于字节顺序标记读取文件:

  private static final Charset[] UTF_ENCODINGS = { Charset.forName("UTF-8"),
      Charset.forName("UTF-16LE"), Charset.forName("UTF-16BE") };

  private static Charset getEncoding(InputStream in) throws IOException {
    charsetLoop: for (Charset encodings : UTF_ENCODINGS) {
      byte[] bom = "\uFEFF".getBytes(encodings);
      in.mark(bom.length);
      for (byte b : bom) {
        if ((0xFF & b) != in.read()) {
          in.reset();
          continue charsetLoop;
        }
      }
      return encodings;
    }
    return Charset.defaultCharset();
  }

  private static String readText(File file) throws IOException {
    Closer res = new Closer();
    try {
      InputStream in = res.using(new FileInputStream(file));
      InputStream bin = res.using(new BufferedInputStream(in));
      Reader reader = res.using(new InputStreamReader(bin, getEncoding(bin)));
      StringBuilder out = new StringBuilder();
      for (int ch = reader.read(); ch != -1; ch = reader.read())
        out.append((char) ch);
      return out.toString();
    } finally {
      res.close();
    }
  }
Run Code Online (Sandbox Code Playgroud)

用法:

  public static void main(String[] args) throws IOException {
    System.out.println(readText(new File("chinese.txt")));
  }
Run Code Online (Sandbox Code Playgroud)

(System.out使用默认编码,因此它是否打印任何合理的取决于您的平台和配置.)