问题描述
我正在尝试将 Unicode 转换为 ISO_8859_1。在 Java 字符串变量中声明 Unicode 时很容易,例如
String myString = "\u00E9checs";
byte[] bytesOfString = myString.getBytes();
String encoded_String = new String(bytesOfString,StandardCharsets.ISO_8859_1);
System.out.println(encoded_String);
输出:
échecs
到目前为止一切顺利,但是当我尝试转换保存在文件中的相同文本时,它并没有按原样转换打印,这里我附上了从文件中读取并执行转换的代码。
String path = "st.txt"; //where st.txt contains only one line i.e. \u00E9checs
FileInputStream inputStream = null;
Scanner sc = null;
try {
inputStream = new FileInputStream(path);
sc = new Scanner(inputStream);
while (sc.hasNextLine()) {
byte[] bytesOfString = sc.nextLine().getBytes();
String encoded_String = new String(bytesOfString,StandardCharsets.ISO_8859_1);
System.out.println(encoded_String);
}
if (sc.ioException() != null) {
throw sc.ioException();
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (sc != null) {
sc.close();
}
}
输出:
\u00E9checs
注意: 这是一个测试代码,因此我在文件中使用了一行;我需要在一个大文件上应用相同的过程,因为我使用 Scanner Class 来节省内存利用率。
有人能指导我如何为文件中的文本实现与 Unicode 直接在 Java String 变量中声明时得到的结果相同的结果吗?
预先感谢您并期待您的早日回复。
解决方法
这就是问题所在:
byte[] bytesOfString = sc.nextLine().getBytes();
String encoded_String = new String(bytesOfString,StandardCharsets.ISO_8859_1);
所以:
-
文件中有大约 8859-1 个字节
-
扫描仪在假设它们是 Unicode 的情况下读取它们
-
然后将 Unicode 数据转换为一些 UTF-8 字节
-
然后将字节转换为 Unicode,假装它们是 8859-1
您应该使用需要 8859-1 输入的扫描仪:
new Scanner(inputstream,StandardCharsets.ISO_8859_1);
然后 nextLine 会做正确的转换;不再需要处理代码。