I am a little confused here.
I would like to do something like this:
- create some kind of buffer I can write into
- clear the buffer
- use a printf()-like function several times to append a bunch of stuff into the buffer based on some complicated calculations I only want to do once
- use the contents of the buffer and print it to several
PrintStreamobjects - repeat steps 2-4 as necessary
e.g.:
SuperBuffer sb = new SuperBuffer(); /* SuperBuffer is not a real class, so I don't know what to use here */ PrintStream[] streams = new PrintStream[N]; /* ... initialize this array to several streams ... */ while (!done) { sb.clear(); sb.printf('something %d something %d something %d', value1, value2, value3); if (some_complicated_condition()) sb.printf('something else %d something else %d', value4, value5); /* ... more printfs to sb ... */ for (PrintStream ps : streams) ps.println(sb.getBuffer()); }
It looks like wrapping a PrintWriter around StringWriter will do what I want for the sb object above, except there’s no clear() method. I suppose I could create a new PrintWriter and StringWriter object each time through the loop, but that seems like a pain. (in my real code I do this in several places, not just once in one loop…)
I’ve also used java.nio.CharBuffer and other NIO buffers a lot, and that seems like a promising approach, but I’m not sure how I can wrap them with an object that will give me printf() functionality.
any advice?
ah: I think I’ve got it. The
Formatterclass has aformat()method that’s likeprintf(), and it can be constructed to wrap around any kind of object that implementsAppendable.CharBufferimplementsAppendable, and I canclear()or read out the contents of theCharBufferas necessary.