BufferedInputStreamstring转换?
可能重复:
在Java中,如何将InputStream读取/转换为string?
嗨,我想把这个BufferedInputStream到我的string,我怎么能做到这一点?
BufferedInputStream in = new BufferedInputStream(sktClient.getInputStream() ); String a= in.read();
BufferedInputStream in = new BufferedInputStream(sktClient.getInputStream()); byte[] contents = new byte[1024]; int bytesRead = 0; String strFileContents; while((bytesRead = in.read(contents)) != -1) { strFileContents += new String(contents, 0, bytesRead); } System.out.print(strFileContents);
番石榴 :
new String(ByteStreams.toByteArray(inputStream),Charsets.UTF_8);
与Commons / IO :
IOUtils.toString(inputStream, "UTF-8")
我build议你使用apache的commons IOUtils
String text = IOUtils.toString(sktClient.getInputStream());
请遵循下面的代码
让我知道结果
public String convertStreamToString(InputStream is) throws IOException { /* * To convert the InputStream to String we use the * Reader.read(char[] buffer) method. We iterate until the 35. * Reader return -1 which means there's no more data to 36. * read. We use the StringWriter class to produce the string. 37. */ if (is != null) { Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader = new BufferedReader( new InputStreamReader(is, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { is.close(); } return writer.toString(); } else { return ""; } }
谢谢,Kariyachan
如果你不想自己写(所有你不应该) – 使用一个库来为你做。
Apache commons-io就是这么做的 。
使用IOUtils.toString(InputStream)或IOUtils.readLines(InputStream)如果你想更好的控制。
快速谷歌search“java bufferedinputstreamstring”抛出了很多的例子。 这一个应该做的伎俩。