My Question is a design question. Should I use a StringBuilder and read the file line-by-line, or should I replace?
I’m developing a way to read text from a file. Within the file there can be @@GOTO:"C:\path\to\more.txt"@@. I want to replace everything between the two @@s with the contents of C:\path\to\more.txt. Also, within more.txt there could be another @@GOTO:"C:\path\to\evenmore.txt"@@. So I’m thinking doing this recursively would be the best.
I’m thinking of something like this:
private String replaceGoTo(Pattern pattern, String xmlString) throws IOException {
Matcher match = pattern.matcher(xmlString);
while (match.find()) {
String replacText = IOHelper.fileToString(match.group(2));
String insert = replaceGoTo(pattern, replacText);
xmlString = xmlString.replace(match.group(1), insert);
}
return xmlString;
}
But I wonder if that’s the most effective way to do it because I’m not using a StringBuilder and I could potentially have a lot of information in those Strings.
Note It’s not broken, I’m just asking about whether there’s a better way to do it. Thanks!
Honest answer: Use an existing template library like Freemarker or Velocity.
Literal answer:
Matcherhas two methods that come in handy for this kind of situation,appendReplacement()andappendTail(). Both require you to use StringBuffer, which is unfortunate, but it’s the most elegant way to solve such a problem.