0

ファイル内の文字列を置き換えようとすると問題が発生します。私のファイルには次のものがあります:

<!-- Header -->
<header fontName="Arial" size="24"/>
<!-- Content -->
<content>
    <fontName="Arial" size="11"/>
</content>

fontName と size だけを置き換える方法は<!-- Header -->?
これは私の置き換え用のコードです

public class StringReplacement {
     public static void main(String args[])
         {
         try
             {
             File file = new File("file.xml");
             BufferedReader reader = new BufferedReader(new FileReader(file));
             String line = "", oldtext = "";
             while((line = reader.readLine()) != null)
                 {
                 oldtext += line + "\r\n";
             }
             reader.close();
             // replace a word in a file
             //String newtext = oldtext.replaceAll("drink", "Love");

             //To replace a line in a file
             String newtext = oldtext.replaceAll("Arial", "Times New Roman");

             FileWriter writer = new FileWriter("file.xml");
             writer.write(newtext);
             writer.close();
         }
         catch (IOException ioe)
             {
             ioe.printStackTrace();
         }
     }
}

ただし、置換するすべてのテキストを置換するだけです。

4

2 に答える 2

2

これがファイルの形式であることが確実な場合は、次の操作を実行できます。

String newtext = oldtext.replaceAll("header fontName=\"Arial\"", "header fontName=\"Times New Roman\"");

ちなみに、StringBuilder文字列を追加するには a を使用します。

于 2013-03-27T09:09:18.500 に答える
1

読み取りループでは、行が見つかったかどうか(まだ行while((line = reader.readLine()) != null)が見つからないかどうか) をテストし、ヘッダー ブロックでのみ置換を行うことができます。<!-- Header --><!-- Content -->

boolean inHeader == false;
while((line = reader.readLine()) != null) {
    if (line.equals("<!-- Header -->")) {
        inHeader = true;
    } else if (line.equals("<!-- Content -->")) {
        inHeader = false;
    }
    if (inHeader) {
        line = line.replaceAll("Arial", "Times New Roman");
    }
    oldtext += line + "\r\n";
}

そして、行を削除します

String newtext = oldtext.replaceAll("Arial", "Times New Roman");

編集: ヘッダーとコンテンツをハードコーディングするよりも、任意のタグを検出する方がおそらくクリーンです。<!-- (tag) -->これには、タグが等しいかどうかを照合してテストするための正規表現が必要ですが"Header"、もちろん、このアプローチの方が簡単です。

于 2013-03-27T09:12:03.190 に答える