尝试替换文件中的字符串时遇到问题。在我的文件中,我有:
<!-- 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();
}
}
}
但它只是替换所有要替换的文本。