0

これに関する多くの投稿を見てきましたが、これを行うことができません。私はこのようなことをする必要があります..たとえば、2つのファイル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();
}

同じコード ブロックでファイルを 2 回読み取ることを避けるために、メソッドを分離しました。それがあなたの助けになることを願っています、または少なくとも、あなたの要件に手を差し伸べてください. よろしくお願いします。

于 2013-04-09T14:04:19.093 に答える