0

我看过很多关于此的帖子,但我无法做到这一点。我需要做这样的事情..可以说,我有两个文件 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();

请帮忙 !

4

2 回答 2

0

嗯...也许您可以避免创建 BufferedReader 类的实例而只使用 String 类:

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

我刚刚分离了该方法以避免在同一代码块中两次读取文件。我希望它可以帮助您,或者至少可以帮助您满足您的要求。此致。

于 2013-04-09T14:04:19.093 回答
0

这是解决此问题的一种技术:

  1. 打开 a.txt 文件进行阅读。
  2. 打开 b.txt 文件进行阅读。
  3. 打开一个名为 a.new.txt 的输出文件。
  4. 从 a.txt 文件中读取一行。
  5. 如果该行不是所需的行(要替换的行),则将该行写入输出文件,然后转到步骤 4。
  6. 将 b.txt 文件的内容附加到输出文件。
  7. 将 a.txt 的剩余内容附加到输出文件中。
于 2013-04-09T13:55:48.893 回答