Wednesday, December 31, 2008

Java, convert InputStream to String

Convert InputStream to String

public String converInputStreamToString(InputStream inputStream) throws IOException{
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

byte[] b = new byte[4096];
int len = 0;

while ((len = inputStream.read(b)) > 0)
{
byteStream.write(b, 0, len);
}
String outputString = byteStream.toString("UTF-8");

return outputString;
}

Another method:
private String convertToString(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));

StringBuffer sbuf = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
if (line.startsWith( "#" )) {
continue;
}

if (!StringUtils.isSet( line )) {
continue;
}

sbuf.append( line );
}

return sbuf.toString();
}

No comments:

Post a Comment