This is by no means an efficient solution, but it should work just fine for 150 files. If you have SSD it should complete in a blink of an eye.
It assumes you have tags on separate lines and new tag should be inserted after every entry key="mergeTemplates" (if it is not, depending on the case, the code can be slightly modified to use Matcher with chunked read instead of lines or read by two lines to detect second tag).
public void addTextAfterLine(String inputFolder, String prefixLine,
String text) throws IOException {
// iterate over files in input dir
try (DirectoryStream<Path> dirStream = Files
.newDirectoryStream(new File(inputFolder).toPath())) {
for (Path inputPath : dirStream) {
File inputFile = inputPath.toFile();
String inputFileName = inputFile.getName();
if (!inputFileName.endsWith(".xml") || inputFile.isDirectory())
continue;
File outputTmpFile = new File(inputFolder, inputFile.getName()
+ ".tmp");
// read line by line and write to output
try (BufferedReader inputReader = new BufferedReader(
new InputStreamReader(new FileInputStream(inputFile),
StandardCharsets.UTF_8));
BufferedWriter outputWriter = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(
outputTmpFile), StandardCharsets.UTF_8))) {
String line = inputReader.readLine();
while (line != null) {
outputWriter.write(line);
outputWriter.write('\n');
if (line.equals(prefixLine)) {
// add text after prefix line
outputWriter.write(text);
}
line = inputReader.readLine();
}
}
// delete original file and rename modified to original name
Files.delete(inputPath);
outputTmpFile.renameTo(inputFile);
}
}
}
public static void main(String[] args) throws IOException {
final String inputFolder = "/tmp/xml/input";
final String prefixLine = "<entry key=\"mergeTemplates\" value=\"false\"/>";
final String newText =
"<entry key=\"requestable\">\n"
+ " <value>\n"
+ " <Boolean>true</Boolean>\n"
+ " </value>\n"
+ "</entry>\n"
;
new TagInsertSample()
.addTextAfterLine(inputFolder, prefixLine, newText);
}
You can also use an advanced editor (e.g. Notepad++ on Windows), with find and replace in files command. Just replace the line <entry key="mergeTemplates" value="false"/>
with <entry key="mergeTemplates" value="false"/>\n..new entry
.
There are many notes here that you should not process XML with text processing tool. This is true if you are developing a generic system or library, to process unknown files. However, just to achieve a task on your files with known format, there is no need for XML complications and text processing fits just fine.
Preempting comments with the question "how do you know it is not going to be a generic system", I'm pretty confident that while developing a generic production system nobody will ask for "java, perl, Unix sed or any other tool".