How to convert an OutputStream into a string?
20,388
InputStream
and OutputStream
are for byte sequences. Reader
and Writer
are for character sequences, like String
s.
To turn an OutputStream
into a Writer
, do new OutputStreamWriter(outputStream)
, or much better, use new OutputStreamWriter(outputStream, Charset)
to specify a Charset
, which describes a way of converting between characters and bytes.
(The other direction, InputStreamReader
, is similar.)
Author by
Lior
Updated on December 17, 2020Comments
-
Lior over 3 years
This is my client code (J2ME):
SocketConnection sc = (SocketConnection) Connector.open("socket://localhost:4444"); sc.openOutputStream().write("test".getBytes()); sc.close();
And this is my server code (J2SE):
ServerSocket serverSocket = new ServerSocket(4444); Socket clientSocket = serverSocket.accept(); OutputStream os = clientSocket.getOutputStream();
How would I go about creating a string representation of
os
?