InputStream String in java
When obtaining an input stream in Java, you sometimes need to convert the input stream to a String to obtain the content. The following describes how to convert InputStream to a String.
Method 1:
Public String convertStreamToString (InputStream is ){
BufferedReader reader = new BufferedReader (new InputStreamReader (is ));
StringBuilder sb = new StringBuilder ();
String line = null;
Try {
While (line = reader. readLine ())! = Null ){
Sb. append (line + "/n ");
}
} Catch (IOException e ){
E. printStackTrace ();
} Finally {
Try {
Is. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
Return sb. toString ();
}
Method 2:
Public String inputStream2String (InputStream in) throws IOException {
StringBuffer out = new StringBuffer ();
Byte [] B = new byte [4096];
For (int n; (n = in. read (B ))! =-1 ;){
Out. append (new String (B, 0, n ));
}
Return out. toString ();
}
Method 3:
Public static String inputStream2String (InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
Int I =-1;
While (I = is. read ())! =-1 ){
Baos. write (I );
}
Return baos. toString ();
}