Java String from InputStream [duplicate]
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 sim开发者_JS百科ple String
with the complete contents.
How is this done in Java?
Here is a modification of Gopi's answer that doesn't have the line ending problem and is also more effective as it doesn't need temporary String objects for every line and avoids the redundant copying in BufferedReader and the extra work in 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)
.
Here is an example code adapted from here.
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 "";
}
}
You can also use Apache Commons IO library
Specifically, you can use IOUtils#toString(InputStream inputStream) method
You could also use a StringWriter as follows; each read
from your InputStream is matched with a write
(or append
) to the StringWriter, and upon completion you can call getBuffer
to get a StringBuffer which could be used directly or you could get call its toString
method.
Wrap the Stream in a Reader to get locale conversion, and then keep reading while collecting in a StringBuffer. When done, do a toString() on the StringBuffer.
精彩评论