This is\u2019 a sample text file \u2014and it can ....
我使用了 Windows 的默认编码方式保存了这个文件,尽管也有其他的编码方式可用,比如 UTF-8、UTF-16 等。
现在我想写一个简单的 Java 函数,其中我将传入一些输入字符串,并替换所有的 Unicode 字符为相应的 ASCII 值。
例如:\u2019 应该被替换为 "'",\u2014 应该被替换为 "-" 等等。
观察: 当我创建一个像这样的字符串文字时
String s = "This is\u2019 a sample text file \u2014and it can ....";
我的代码运行得很好,但是当我从文件中读取它时,它就无法运行。我知道在Java中String使用UTF-16编码。
下面是我用来读取输入文件的代码。
FileReader fileReader = new FileReader(new File("C:\\input.txt"));
BufferedReader bufferedReader = new BufferedReader(fileReader)
String record = bufferedReader.readLine();
我也尝试使用
InputStream并将字符集设置为UTF-8
,但结果仍然相同。
替换代码:
public static String removeUTFCharacters(String data){
for(Entry<String,String> entry : utfChars.entrySet()){
data=data.replaceAll(entry.getKey(), entry.getValue());
}
return data;
}
地图:
utfChars.put("\u2019","'");
utfChars.put("\u2018","'");
utfChars.put("\u201c","\"");
utfChars.put("\u201d","\"");
utfChars.put("\u2013","-");
utfChars.put("\u2014","-");
utfChars.put("\u2212","-");
utfChars.put("\u2022","*");
有人能帮我理解这个问题的概念和解决方案吗?
String
中实际显示了哪些16位字符吗?就像这样:for (i=0; i<record.length(), i++) System.out.printf("%04X ",(int)record.charAt(i));
- ajb