In Java Where does the PrintWriter write() method write the data -
import java.io.file; import java.io.printwriter; public class printwriterexample { public static void main(string[] args) throws exception { //data write on console using printwriter printwriter writer = new printwriter(system.out); writer.write("hello world"); system.out.write(65); system.out.write(' '); system.out.flush(); system.out.close(); // writer.flush(); //writer.close(); } }
iam having trouble understanding write() method. description says writes specified byte stream. mean 'this stream'. written? kind of buffer?? mean pass system.out argument printwriter class constructor? in code data buffered? temporary memory created when use writer.write() , system.out.write()? when tried comment , uncomment flush , close methods randomly got results confused me.in particular instance why doesnt "hello world" printed on screen though have flushed , closed buffer. if buffers different when uncomment writer.flush() , writer.close() same result.
system.out
printstream
, aka outputstream
, you're calling printwriter(outputstream out)
constructor.
it equivalent calling printwriter(writer out)
following argument:
new bufferedwriter(new outputstreamwriter(out))
the bufferedwriter
injected performance reasons.
where data buffered?
in bufferedwriter
.
why doesnt "hello world" printed
the "hello world"
text sitting in buffer, , since never flush writer
, it'll never sent downstream system.out
print stream.
what mean pass
system.out
argumentprintwriter
class constructor?
it means text written printwriter
forwarded system.out
. javadoc says: this convenience constructor creates necessary intermediate outputstreamwriter, convert characters bytes using default character encoding.
when uncomment writer.flush() , writer.close() same result.
that because closed system.out
, not accept more output. printwriter
silently ignores error thrown when try. javadoc says: methods in class never throw i/o exceptions, although of constructors may. client may inquire whether errors have occurred invoking checkerror()
.
solution
calling close()
automatically call flush()
, don't need call flush()
before close()
.
calling close()
on printwriter
automatically call close()
on system.out
, don't need that.
remove system.out.flush();
, system.out.close();
, , writer.flush();
, , call writer.close();
.
better yet, should in general never close system.out
, call writer.flush();
, , leave open.
Comments
Post a Comment