简体   繁体   English

如何在文件上编辑行

[英]How to edit line on file

This is my code: 这是我的代码:

public class FileReplace {
    List<String> lines = new ArrayList<String>();
    String line = null;

    public void  doIt() {
        try {
            File f1 = new File("d:/new folder/t1.htm");
            FileReader fr = new FileReader(f1);
            BufferedReader br = new BufferedReader(fr);
            while ((line = br.readLine()) != null) {
                if (line.contains("java"))
                    line = line.replace("java", " ");
                lines.add(line);
            }
            fr.close();
            br.close();

            FileWriter fw = new FileWriter(f1);
            BufferedWriter out = new BufferedWriter(fw);
            for(String s : lines)
                 out.write(s);
            out.flush();
            out.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String args[]) {
        FileReplace fr = new FileReplace();
        fr.doIt();
    }
}

and I have this text: 我有这段文字:

javascript_js javascript_js
java_swing java_swing
java_fx java_fx
kotlin 科特林
python 蟒蛇

I wanna edit java_fx to java . 我想将java_fx编辑为java My code is deleting all content and write java_fx , how do I edit java_fx without erasing all content in file? 我的代码正在删除所有内容并写入java_fx ,如何在不删除文件中所有内容的情况下编辑java_fx

FileWriter fw = new FileWriter(f1, true);

向FileWriter构造函数添加true参数,这将避免重写内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM