BufferedInputStream To String Conversion?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
In Java how do a read/convert an InputStream in to a string?
嗨,我想把这个bufferedInputstream放到我的字符串中,我该怎么做呢?
1 2 |
1 2 3 4 5 6 7 8 9 10 | 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); |
番石榴:
1 |
使用commons/io:
1 | IOUtils.toString(inputStream,"UTF-8") |
我建议您使用Apache Commons ioutils
1 |
请遵循代码
让我知道结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | 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""; } } |
谢谢,卡里亚坎
如果你不想一个人写(你也不应该这样写),那就用一个图书馆来为你写。
Apache Commons IO就是这样做的。
如果需要更精细的控件,请使用ioutils.toString(inputstream)或ioutils.readlines(inputstream)。