【问题标题】:How to edit line on file如何编辑文件中的行
【发布时间】:2018-08-29 17:43:08
【问题描述】:

这是我的代码:

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();
    }
}

我有这段文字:

javascript_js
java_swing
java_fx
科特林
蟒蛇

我想将java_fx 编辑为java。我的代码正在删除所有内容并写入java_fx,如何在不删除文件中所有内容的情况下编辑java_fx

【问题讨论】:

  • 据我所知,简短的回答是你不能。您可以读取每一行并修改您想要的行,但您必须将每一行再次写入文件。

标签: java android file text


【解决方案1】:
FileWriter fw = new FileWriter(f1, true);

在 FileWriter 构造函数中添加 true 参数,这样可以避免重写内容。

【讨论】:

  • 这是编辑文件,并在末尾追加替换文本,但不编辑 java_fx 到 java
  • 我测试了你的代码并且运行良好。但是在 if(line.contains("java")) 中,这将是“java_fx”而不是“java”,因为您想将 java_fx 替换为 java。同样在我看来,如果不删除所有内容就无法编辑文件,您必须找到要替换的单词,然后在某处写入(您添加到 List 集合中)并将所有内容写入文件。您的代码是正确的。
猜你喜欢
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-31
  • 1970-01-01
相关资源
最近更新 更多