Printf () in Java combined with CharBuffer or something like that

I'm a little confused here.

I would like to do something like this:

  • create some kind of buffer that I can write to
  • clear buffer
  • use the printf () function multiple times to add a bunch of stuff to the buffer based on some complex computation that I only want to do once.
  • use the buffer contents and print it with multiple objects PrintStream

  • repeat steps 2-4 as needed

eg:.

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 completing the PrintWriter around the StringWriter will do what I want for the object sb

above, apart from the method clear()

. I suppose I could create a new PrintWriter and StringWriter every time through the loop, but that seems like a pain. (in my real code, I do this in multiple places, not once in a single loop ...)

I've used java.nio.CharBuffer

other NIO buffers as well , and this seems like a promising approach, but I'm not sure how I can wrap them with an object that will give me the printf()

functionality.

any advice?

0


source to share


3 answers


ah: I think I have it. A class Formatter

has a method format()

similar to printf()

, and it can be constructed to wrap any object that implements Appendable

. CharBuffer

implements Appendable

and I can clear()

or as needed read the content CharBuffer

.



+3


source


Why is it painful to create a new buffer in a loop? This is what the garbage collector is for. In any case in transparent () there should be a new distribution under the covers.



If you really want to implement your SuperBuffer, it won't be that hard. Just subclass OutputStream with clear () function and then wrap PrintStream around that. You can use CharBuffer in your superbuffer if you like.

+1


source


Consider subclassing TeeOutputStream, OutputStream (or Writer), which contains your array of streams and delegates. Then wrap up the StreamStream (or PrintWriter) and just call printf (). No need for a temporary buffer or anything else:

PrintStream[] streams = new PrintStream[N]; // any output streams really
PrintStream ps = new PrintStream(new TeeOutputStream(streams));

while (!done)
{
    ps.printf("something %d something %d something %d",
              value1, value2, value3);    
    if (some_complicated_condition())
        ps.printf("something else %d something else %d", value4, value5);
    ps.println();
}

      

0


source







All Articles