InputStream to String

Posted by Jagadeesh VP | Posted in ,


import java.io.InputStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class StreamToString {

public static void main(String[] args) throws Exception {
StreamToString sts = new StreamToString();

InputStream is = sts.getClass().getResourceAsStream("/data.txt");

/*
* Call the method to convert the
* stream to string
*/
System.out.println(sts.convertStreamToString(is));
}

public String convertStreamToString(InputStream is) throws IOException {
/*
* To convert the InputStream to String
* we use the BufferedReader.readLine()
* method. Each line will appended to a
* StringBuilder and returned as String.
*/
if (is != null) {
StringBuilder sb = new StringBuilder();
String line = null;

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while ((line = reader.readLine()) != null)
sb.append(line).append("\n");

} catch (Exception e) {
//Do something..
} finally {
is.close();
}
return sb.toString();
} else {
return "";
}
}
}

Comments (0)

Post a Comment