【问题标题】:Replacing character in a string after reading from a file java从文件java读取后替换字符串中的字符
【发布时间】:2015-11-09 04:31:24
【问题描述】:

所以我正在编写一个程序,该程序将从文件中读取输入,将所有 html 标记替换为 >、大于和

public void rewrite(String from, String to) {
    File f = new File(from);
    File t = new File(to);
    try {
        Scanner s = new Scanner(f);
        FileWriter fw = new FileWriter(to);
        while (true) {
            if (s.hasNext()) {
                String a = s.next();
                if (a.contains("<") || a.contains(">") || a.contains("&")) {
                    a.replace("<", "&lt;,");
                    a.replace(">","&gt;,");
                    a.replace("&","amp;,");

                }
                fw.append(a);
            } else {
                break;
            }
        }
        fw.close();
        s.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}

编辑:It is a warning not a compile time error nor a runtime error

【问题讨论】:

  • 包含确切的错误信息怎么样?运行时还是编译时?
  • 看起来应该可以,但您可能想尝试使用String.replaceAll() 而不是String.replace()
  • 您是否尝试在替换前后打印字符串'a'...

标签: java string file-io


【解决方案1】:

警告是因为字符串不变性

你应该使用

a = a.replace("<", "&lt;,");
a = a.replace(">","&gt;,");
a = a.replace("&","amp;,");

否则,被替换的字符串会丢失,原字符串不会被修改

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-03
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    • 2021-01-19
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多