Pregunta

I'd like to use a PrintWriter or PrintStream to write formatted strings out to an outputstream (for which I have no control over the creation). However flushing the underlying OutputStream has a big performance hit.

Does a PrintWriter / PrintStream need to be flushed.

If I need to flush the PrintStream / PrintWriter; can I do so without flushing the underlying OutputStream, or will I need to create a "flush protecter" OutputStream to wrap the underlying stream?

To try to be a little clearer on this I want to implement

 public void writeSomeString(OutputStream foo);

But this method may be called many times for the same OutputStream (foo). Each call will have to construct its own PrintWriter. I know it's ugly to do so but I have no control over the interface or the creation of foo.

I'm trying to avoid each method having to flush foo just to flush its own PrintWriter / PrintStream.

So I want to:

public void writeSomeString(OutputStream foo) {
    PrintStream s = new PrintStream(foo);
    s.println("bar");
    // other code
}

I want to completely avoid this method flushing foo

¿Fue útil?

Solución

PrintWriter needs to be flushed in the following condition:

ServerSocket s = new ServerSocket(4444);

Socket incoming = s.accept();

OutputStream output = s.getOutputStream();

PrintWriter pw = new PrintWriter(output,true);

System.out.println(pw.write(new Scanner(System.in).nextLine()));

2nd parameter in PrintWriter constructor is flush which accepts boolean datatype, we need to flush the data, so it gets thrown on the Console even if the buffer is not full.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top