我目前正在尝试编写一小段Java,它需要读取文件,搜索要更改的特定行。问题是要更改的行在文件中不是唯一的,因为它是类似 XML 的结构的一部分,因此嵌套在另一个标记内。
例如:
<tag1>Tag Text</tag1>
<example>Value</example>
<tag2>Tag Text</tag2>
<example>Value</example> //Want to change only this Value.
<tag3>Tag Text</tag3>
<example>Value</example>
在此示例中,我只想更改 <tag2>
下示例标记中的值不改变其他值。
所以我正在尝试搜索<tag2>
首先,一旦找到,我就会搜索 <value>
,编辑该值,然后保留文件的其余部分不变。
目前,我正在使用 BufferedReader/Writer 将文件复制到临时文件,更改值,然后删除旧文件,用新文件替换它。
参见下面的代码:
public class Replace {
public static void main(String[] args) {
new Replace().replace();
}
public void replace() {
//All input data to be changed, testing purposes.
String rootFolder = "Some root";
String fileName = "some filename";
String newValue = "<Value>New Value</Value>";
//Strings to find location in the file that needs to be amended.
String firstFileLine = "<tag2>";
String secondFileLine = "<Value>";
String oldFileName = rootFolder + fileName;
String tmpFileName = "temp.txt";
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line, secondLine;
while ((line = br.readLine()) != null) {
if (line.contains(firstFileLine)){
//This is an attempt to try solve it, but this still replaced all <Value> tags in the file
while ((secondLine = br.readLine()) != null) {
if (secondLine.contains(secondFileLine))
secondLine = secondLine.replace(secondFileLine, newValue);
bw.write(secondLine+"\n");
}
}
bw.write(line+"\n");
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
// Once everything is complete, delete old file..
File oldFile = new File(oldFileName);
oldFile.delete();
// And rename tmp file's name to old file name
File newFile = new File(tmpFileName);
newFile.renameTo(oldFile);
}
}
这是解决此问题的最佳方法吗?也欢迎任何其他建议!
提前感谢大家!
W
最佳答案
你的方法是正确的,你需要读取旧文件,进行替换并将其写回。当前算法中不正确的部分是,在 while 循环中,当到达 tag2 末尾时需要停止。
此外,如果内容是 XML,您应该考虑使用 XML 解析器来执行此操作。
while ((secondLine = br.readLine()) != null) {
if (secondLine.contains(endOfFirstLine)) {
bw.write(secondLine+"\n");
break;
}
if (secondLine.contains(secondFileLine))
secondLine = secondLine.replace(secondFileLine, newValue);
bw.write(secondLine+"\n");
}
关于java - 从某个点读取/编辑文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32757037/