我编写了一个小程序来读取文件,找到某个字符串,替换它,然后写入一个新文件。这是我的代码。
public static void main(String[] args) {
String line;
try {
FileInputStream fstream = new FileInputStream("a.xml");
BufferedInputStream bis = new BufferedInputStream(fstream);
DataInputStream in = new DataInputStream(bis);
Pattern p = Pattern.compile("someregex");
StringBuilder content = new StringBuilder();
while (in.available() != 0) {
line = in.readLine();
Matcher matcher = p.matcher(line);
if (matcher.find()) {
String filtered = matcher.group();
int len = filtered.length() - 8;
String city = filtered.substring(7, len);
line = line.replaceAll("someregex", city);
content.append(line).append("\n");
} else {
content.append(line).append("\n");
}
}
in.close();
BufferedWriter out = new BufferedWriter(new FileWriter("b.xml"));
out.write(content.toString());
out.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
问题是文件包含一些 unicode 字符而 Java 没有保留它。我有这样一句话:“可爱的槟城东方之旅”。 Java 将其写为“可爱的槟城东部和东方之旅”。如何保留unicode字符?
最佳答案
您必须使用InputStreamReader
。有几种方法可以做到这一点,但这是一种:http://docs.oracle.com/javase/tutorial/i18n/text/stream.html
他们的例子是:
FileInputStream fis = new FileInputStream("test.txt");
InputStreamReader isr = new InputStreamReader(fis, "UTF8");
编辑:根据 Joop 在评论中的建议,应使用现代版本,因此 "UTF-8"
。
关于java - 从文本文件中读取错误字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17297591/