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
How to convert an OutputStream into a string?
提问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
InputStream
and OutputStream
are for byte sequences. Reader
and Writer
are for character sequences, like String
s.
InputStream
和OutputStream
用于字节序列。Reader
和Writer
用于字符序列,如String
s。
To turn an OutputStream
into 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.
要打开一个OutputStream
到Writer
,这样做new OutputStreamWriter(outputStream)
,或者多好,使用new OutputStreamWriter(outputStream, Charset)
指定Charset
,它描述字符和字节之间转换的一种方式。
(The other direction, InputStreamReader
, is similar.)
(另一个方向 ,InputStreamReader
类似。)