2

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?

Lior
  • 5,454
  • 8
  • 30
  • 38

1 Answers1

7

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

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • I'm not sure I understand. Do you mean I should create an OutputStreamWriter using the OutputStream I get from clientSocket? If so, what do I do with it? How to I get the content of the output stream? – Lior Dec 17 '12 at 00:20
  • You don't "get contents of an output stream." You get contents of an _input_ stream. That's...why it's called input. (In which case you'll probably want an `InputStreamReader`, not an `OutputStreamWriter`.) – Louis Wasserman Dec 17 '12 at 00:45