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?
I have an InputSteam
and need to simply get a single simple String
with the complete contents.
How is this done in Java?
这是对Gopi的答案的一种修改,它没有行结束问题,并且更有效,因为它不需要每行都有临时的String对象,并且避免了BufferedReader中的冗余复制和readLine()中的额外工作。
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();
}
You need to construct an InputStreamReader
to wrap the input stream, converting between binary data and text. Specify the appropriate encoding based on your input source.
Once you've got an InputStreamReader
, you could create a BufferedReader
and read the contents line by line, or just read buffer-by-buffer and append to a StringBuilder
until the read()
call returns -1.
The Guava library makes the second part of this easy - use CharStreams.toString(inputStreamReader)
.
You can also use Apache Commons IO library
Specifically, you can use IOUtils#toString(InputStream inputStream) method
链接地址: http://www.djcxy.com/p/13728.html上一篇: 一次读取inputStream