java - 无法在 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();
}
解决方案
首先,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
.
推荐阅读
- javascript - 是否有任何用于角度选择的国家/地区货币的软件包?
- php - Jquery & PHP 不指向标头函数
- java - 如何将变量值添加到java中另一个变量的名称?
- flutter - 如何在 Hasura graphql 和 Netlify 中处理多个请求?
- java - java.lang.IllegalArgumentException 参数值 [com..schoolmanagement.model.exam.QuestionPaper@7d78f8f] 与预期类型不匹配
- python - 以下程序用于求解二次方程:[ax²+bx+c=0]。你能发现上面的代码有什么问题吗?
- sql - 如何将列中的字符串转换为同一列中的对象json sql server
- c++ - 错误 LNK2001:未解析的外部符号 __CxxFrameHandler4 和 __GSHandlerCheck_EH4
- android - 带有图像的 Android 回收站视图
- apache-spark - Graph 是否在 pyspark 上适用于 Spark 3.0+