首页 > 解决方案 > 无法在 java 中将 UTF-8 字符串转换并保存为 ANSI

问题描述

这是我的代码。我必须以 UTF-8 将字符串写入控制台,但将字符串保存在 ANSI 中。当我打开文件时,它是 UTF-8 格式的。我该怎么办?

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
String message = bufferedReader.readLine();
bufferedReader.close();
String utfString = new String(message.getBytes(), "UTF-8");
String ansiMessage = new String(utfString.getBytes(), "WINDOWS-1251");
writeToFile(ansiMessage, "ANSI.txt", "WINDOWS-1251");
private static void writeToFile(String string, String path, String enc) throws IOException {
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), enc));
    writer.write(string);
    writer.close();
}

标签: javautf-8ansi

解决方案


首先,getBytes()以默认字符集(通常为 UTF-16)返回字符串的字节。其次,new String(bytes[], string)将字节解释为提供的字符集中的字符串,它不会转换它们。所以:

new String(message.getBytes(), "UTF-8")

尝试将 UTF-16 字符串读取为 UTF-8,不好。然后:

new String(utfString.getBytes(), "WINDOWS-1251")

尝试将生成的字符串读取为 WINDOWS-1251,同样糟糕。

我确定此时您的字符串已被破坏。

您可以调用getBytes(Charset)以获取所需字符集中的字符串字节。但是在您的情况下,您甚至不需要这样做,因为您的 writeToFile(...) 方法在写入文件时已经进行了字符集转换,因此您只需将原始的message.


推荐阅读