• 替换一个文件内的某个字符


    先看这种写法:

    public static void main(String[] args) throws IOException {
            
            try {
                FileReader r = new FileReader("d:/ti.txt");
            StringBuilder sb = new StringBuilder();
            char[] temp = new char[1];
            int read = r.read(temp);
            while(read!=-1){
                sb.append(temp);
            }
            String strAfter = sb.toString().replace("c", "x");
            FileWriter w = new FileWriter("d:/titi.txt");
            w.write(strAfter);
            r.close();
            w.close();
                
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }

    debug:

    read为1所以while就成了无限循环,内存溢出了

    当这样修改后:

    public static void main(String[] args) throws IOException {
            
            try {
                FileReader r = new FileReader("d:/ti.txt");
            StringBuilder sb = new StringBuilder();
            char[] temp = new char[1];
            //r.read(temp)放到while的里
            while((r.read(temp))!=-1){
                sb.append(temp);
            }
            String strAfter = sb.toString().replace("c", "x");
            FileWriter w = new FileWriter("d:/titi.txt");
            w.write(strAfter);
            r.close();
            w.close();
                
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }

    所以,要一直取一直取一直取的应该放在while里,不能放while外

  • 相关阅读:
    MongoDB
    前端框架之vue初步学习
    mysql再回首
    oracle之回顾二
    oracle再回首
    springboot之对之前的补充
    springCloud学习
    springboot-ssm的pom.xml
    MyCat
    11.Java反射机制 哦对了,前面的序号来自随笔关于编程之路的思索第一篇
  • 原文地址:https://www.cnblogs.com/lonely-buffoon/p/5575588.html
Copyright © 2020-2023  润新知