How to convert InputStream to String in java?

Many times we need to convert InputStream to String, Now lets see how we can convert InputStream to Java String.
We can use StringWriter class to get the String from the InputStream. When we get the input stream then we can read this inputStream using InputStreamReader and BufferedReader as follows :


reader = new BufferedReader( new InputStreamReader( inputStream ,"UTF-8" ) );

When we get this BufferedReader object then we can read it line by line and put it in character array and store it in StringWriter object. This StringWriter object can return the String using toString method.


Following example shows how to convert InputStream to String :


public class InputStreamToStringDemo {


public static void main(String[] args){


InputStreamToStringDemo streamToString = new InputStreamToStringDemo();

try{
InputStream inputStream = new FileInputStream("C:\\test1.txt");
String strFromIS = streamToString.convertInputStreamToString( inputStream );
System.out.println( "strFromIS : "+strFromIS);
}catch(Exception es){

}
}

String convertInputStreamToString( InputStream inputStream ){

String strText = "";
if( inputStream != null ){
StringWriter sw = new StringWriter();
char[] bufText = new char[1024];
BufferedReader reader = null;
try{
reader = new BufferedReader( new InputStreamReader( inputStream ,"UTF-8" ) );
int charRead = 0;

while((charRead = reader.read( bufText )) != -1) {
sw.write(bufText, 0, charRead);
}
strText = sw.toString();
}catch(Exception es){
es.printStackTrace();
}finally{

try{
reader.close();
}catch( IOException es ){

}
try{
inputStream.close();
}catch( IOException es ){

}
try{
sw.close();
}catch( IOException es ){

}

}

}
return strText;

}
}
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment