Java String from InputStream
Possible Duplicates:
How do I convert an InputStream to a String in Java?
In Java how do a read an input stream in to a string?
我有一个
这是如何在Java中完成的?
这里是对gopi答案的修改,它不存在行尾问题,而且更有效,因为它不需要每行临时的字符串对象,并且避免了bufferedreader中的冗余复制和readline()中的额外工作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public static String convertStreamToString( InputStream is, String ecoding ) throws IOException { StringBuilder sb = new StringBuilder( Math.max( 16, is.available() ) ); char[] tmp = new char[ 4096 ]; try { InputStreamReader reader = new InputStreamReader( is, ecoding ); for( int cnt; ( cnt = reader.read( tmp ) ) > 0; ) sb.append( tmp, 0, cnt ); } finally { is.close(); } return sb.toString(); } |
您需要构造一个
一旦你得到了一个
guava库是这个易于使用的
您还可以使用Apache Commons IO库
具体来说,您可以使用ioutils toString(inputstream inputstream)方法
下面是从这里改编的示例代码。
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 | public String convertStreamToString(InputStream is) throws IOException { /* * To convert the InputStream to String we use the BufferedReader.readLine() * method. We iterate until the BufferedReader return null which means * there's no more data to read. Each line will appended to a StringBuilder * and returned as String. */ if (is != null) { StringBuilder sb = new StringBuilder(); String line; try { BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8")); while ((line = reader.readLine()) != null) { sb.append(line).append(" "); } } finally { is.close(); } return sb.toString(); } else { return""; } } |
您也可以按如下方式使用StringWriter;输入流中的每个
将流包装在读取器中以获取区域设置转换,然后在StringBuffer中收集时继续读取。完成后,对StringBuffer执行ToString()。