How can I “modify” an InputStream? I have a file as input, I would like to modify some variable and forward a new InputStream.
For example, the initial InputStream contains Hello ${var}. Then I want to “modify” this InputStream with var = “world”, resulting an InputStream Hello world.
What’s the best practice to do this? Thanks.
The
java.iois one and all decorator pattern. Make use of it and create a class whichextends InputStream(maybeDataInputStreamor better, someReadersince you’re actually interested in characters, not in bytes, but ala), add a constructor which takes the originalInputStreamand override theread()methods to read the original stream in, buffer it to a certain degree (e.g. from${until with firstnext}) and then determine the key and return the modified data instead.If you call your new class
FormattedInputStreamor so, then you could returnnew FormattedInputStream(originalInputStream)to the enduser instead and have the enduser still just assign and use it as anInputStream.