Note that there are some explanatory texts on larger screens.

plurals
  1. POprintf() functionality in Java combined with a CharBuffer or something like it
    text
    copied!<p>I am a little confused here.</p> <p>I would like to do something like this:</p> <ol> <li>create some kind of buffer I can write into</li> <li>clear the buffer</li> <li>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</li> <li>use the contents of the buffer and print it to several <code>PrintStream</code> objects</li> <li>repeat steps 2-4 as necessary</li> </ol> <p>e.g.:</p> <pre><code>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()); } </code></pre> <p>It looks like wrapping a <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/io/PrintWriter.html" rel="nofollow noreferrer">PrintWriter</a> around <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/io/StringWriter.html" rel="nofollow noreferrer">StringWriter</a> will do what I want for the <code>sb</code> object above, except there's no <code>clear()</code> 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...)</p> <p>I've also used <code>java.nio.CharBuffer</code> 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 <code>printf()</code> functionality.</p> <p>any advice?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload