这是对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();
}
Run Code Online (Sandbox Code Playgroud)
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).
这是改编自此处的示例代码。
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("\n");
}
} finally {
is.close();
}
return sb.toString();
} else {
return "";
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10269 次 |
| 最近记录: |