java 如何将 OutputStream 转换为字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13906776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:23:36  来源:igfitidea点击:

How to convert an OutputStream into a string?

javajava-meoutputstream

提问by Lior

This is my client code (J2ME):

这是我的客户端代码(J2ME):

SocketConnection sc = (SocketConnection) Connector.open("socket://localhost:4444");
sc.openOutputStream().write("test".getBytes());
sc.close();

And this is my server code (J2SE):

这是我的服务器代码(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?

我将如何创建 的字符串表示os

回答by Louis Wasserman

InputStreamand OutputStreamare for byte sequences. Readerand Writerare for character sequences, like Strings.

InputStreamOutputStream用于字节序列。ReaderWriter用于字符序列,如Strings。

To turn an OutputStreaminto a Writer, do new OutputStreamWriter(outputStream), or muchbetter, use new OutputStreamWriter(outputStream, Charset)to specify a Charset, which describes a way of converting between characters and bytes.

要打开一个OutputStreamWriter,这样做new OutputStreamWriter(outputStream),或者好,使用new OutputStreamWriter(outputStream, Charset)指定Charset,它描述字符和字节之间转换的一种方式。

(The other direction, InputStreamReader, is similar.)

(另一个方向 ,InputStreamReader类似。)