有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java:查找并替换一行

我看过很多关于这方面的帖子,但我无法做到这一点。我需要做一些像这样的事情。。比方说, 我有两个文件a.txt,b.txt。 我应该在a.txt中搜索字符串/行,并将其替换为b.txt的内容。 我认为它只是几行简单的代码。我尝试了下面的代码,但它不工作

File func = new File("a.txt");
BufferedReader br = new BufferedReader(new FileReader(func));

String line;

while ((line = br.readLine()) != null) {
    if (line.matches("line to replace")) {
        br = new BufferedReader(
                new FileReader(func));
        StringBuffer whole = new StringBuffer();
        while ((line = br.readLine()) != null) {
            whole.append(line.toString() + "\r\n");
        }
        whole.toString().replace("line to replace",
                "b.txt content");
        br.close();

        FileWriter writer = new FileWriter(func);
        writer.write(whole.toString());
        writer.close();
        break;
    }
}
br.close();

请帮忙


共 (2) 个答案

  1. # 1 楼答案

    以下是解决此问题的技巧:

    1. 打开a.txt文件进行读取
    2. 打开b.txt文件进行读取
    3. 打开名为a.new的输出文件。txt
    4. 从a.txt文件中读取一行
    5. 如果该行不是所需的行(要替换的行),请将该行写入输出文件,然后转至步骤4
    6. 将b.txt文件的内容附加到输出文件中
    7. 将a.txt的剩余内容追加到输出文件中
  2. # 2 楼答案

    嗯。。。也许可以避免创建BufferedReader类的实例,而只使用字符串类:

    public class Sample {
    
    public static void main(String[] args) throws Exception{
        File afile = new File("/home/mtataje/a.txt");
    
        String aContent = getFileContent(afile);
        System.out.println("A content: " );
        System.out.println(aContent);
        System.out.println("===================");
        if (aContent.contains("java rulez")) {
            File bfile = new File("/home/mtataje/b.txt");
            String bContent = getFileContent(bfile);
            String myString = aContent.replace("java rulez", bContent);
            System.out.println("New content: ");
            System.out.println(myString);
            afile.delete();//delete old file
            writeFile(myString);//I replace the file by writing a new one with new content
        }
    }
    
    public static void writeFile(String myString) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter(new File("/home/mtataje/a.txt")));
        bw.write(myString);
        bw.close();
    }
    
    public static String getFileContent(File f) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(f));
    
        String line;
        StringBuffer sa = new StringBuffer();
        while ((line = br.readLine()) != null) {
           sa.append(line);
           sa.append("\n");
        }   
        br.close();
        return sa.toString();
    }
    

    我刚刚分离了这个方法,以避免在同一代码块中读取文件两次。我希望它能帮助你,或者至少帮你满足你的要求。致以最良好的祝愿