zoukankan      html  css  js  c++  java
  • 替换一个文件内的某个字符

    先看这种写法:

    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外

  • 相关阅读:
    php解析文本文件呈现在表格上
    nyoj 1058部分和问题
    nyoj 488素数环
    nyoj 82迷宫寻宝(一)
    nyoj58最少步数
    nyoj 325 zb的生日
    nyoj 20 吝啬的国度
    nyoj 349 Sorting It All Out
    nyoj 284
    PPT基础整理
  • 原文地址:https://www.cnblogs.com/lonely-buffoon/p/5575588.html
Copyright © 2011-2022 走看看