java - 从文本文件中读取错误字符

标签 java

我编写了一个小程序来读取文件,找到某个字符串,替换它,然后写入一个新文件。这是我的代码。

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/

相关文章:

java - 我想在java中将表数据打印到Textarea中

Java apache POI java.lang.IllegalArgumentException : Position 21504 past the end of the file

java - 服务器的 Bounce 和 BootUp 有什么区别?

java - 我应该为未经身份验证的用户使用 session 吗?

java - JFrame 使用不同的 System.in 卡住

java - 给定的 html 文件只提取有意义的文本

Java泛型在集合及其子类型中扩展和 super 实现

java - JPA:选择实体的子集不会加载@OneToOne 属性

java - 卡在 "java.util.ConcurrentModificationException"

java - 从数组列表添加元素到 List<List<String>>