Lior
Lior

Reputation: 5674

How to convert an OutputStream into a string?

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?

Upvotes: 2

Views: 26042

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198481

InputStream and OutputStream are for byte sequences. Reader and Writer are for character sequences, like Strings.

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.)

Upvotes: 7

Related Questions