Can I use both PrintWriter and BufferedOutputStrea

2019-02-28 14:10发布

问题:

Can I use both PrintWriter and BufferedOutputStream on the same outputstream?

The situation is this:

I'm having a SSLSocket program and I want to be able to transfer both Strings and byte [] over the socket at different points in time easily without having to cast byte [] to string etc, however, PrintWriter only allows me to transfer Strings and BufferedOutputStream only allows me to transfer bytes.

回答1:

PrintWriter is just a wrapper around original OutputStream. BufferedOutputStream is a wrapper around OutputStream too. So you can use both. Why not?

Single thing you should to consider - you should be carefull working with both stream and writer in multithread environment because you can get unpredictable result.

The java.io.Writer class (super class for PrintWriter) use itself as a lock object. So you can also probably use it to synchronize multiple threads.



回答2:

That's ok, but you have to make sure to flush them in the right order. You can also use the PrintWriter on top of the BufferedOutputStream.



回答3:

I would use a DataOutputStream (possibly wrapping a BufferedOutputStream). It allows you to transfer byte[], int, double String and many other types. To send the byte[] you may want to send the length first as a int or short.



标签: java sockets ssl