tpdietz
tpdietz

Reputation:

Fastest way to replace data in Java

I need to write a Java method that will:

For example, The original HTML could have a page header, the marker and a page footer. I would want to get that HTML and replace the marker with page content, like a blog posting.

My main concerns are speed and functionality. Since the original HTML and the HTML to be injected into the original HTML could be quite large, I need some advice.

I know I could use Strings and use String.replace(), but I'm concerned about the size limitations of a String and how fast that would perform.

I'm also thinking about using the Reader/Writer objects, but I don't know if that would be faster or not.

I know there is a Java Clob object, but I don’t really see if it can be used for my particular situation.

Any ideas/advice would be welcome.

Thanks,

Tim

Upvotes: 0

Views: 660

Answers (3)

Will Hartung
Will Hartung

Reputation: 118611

Stream the data in with a Reader, parse it on the fly to find your tags, and replace the data as it goes by while you are streaming the data out with a Writer.

Yes, you have to write a parser to do this.

Do not load it in to a big buffer, do searches and regexes and whatever on the buffer, and then write it out. Processing the data once is the fastest thing you can do.

If you have data later in the file that will fill in spots higher in the file, then your stuck sucking the whole thing in.

Finally, why aren't you just using something like Apache Velocity?

Upvotes: 2

Dutow
Dutow

Reputation: 5668

StringBuilder (not threadsafe) and StringBuffer (threadsafe) are the two basic constructions for String manipulation. But if you are reading your data from a stream it is probably better if you do it on the fly. (read lines, look for marker, if found write content instead of it)

Upvotes: 0

Anon
Anon

Reputation: 2348

How big is your HTML? A gigabyte? A megabyte? 100k? 10k? For all but the first, string manipulation will be just fine. If that answer doesn't satisfy you, then use indexOf() to find the start and end of the marker, and use substring() to write the portions of the original string before and after.

Upvotes: 1

Related Questions