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
这里有几个因素在起作用:
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使用默认编码,因此它是否打印任何合理的取决于您的平台和配置.)
| 归档时间: |
|
| 查看次数: |
21195 次 |
| 最近记录: |