How to convert Inputstream as String using Java

In this article we will discuss about. How Java can do conversion from InputStream Object into String using Java core libraries.

  package com.onlinecodegeek.java.core;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class InputStreamToStringExample {
public static void main(String[] args) throws IOException {
InputStream is = new ByteArrayInputStream("file content..blah blah".getBytes());
String result = getStringFromInputStream(is);
System.out.println(result);
System.out.println("Done");
}
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}

Vijay D

Hi, I have written and developed this post so that most of people will be benefited. I'm committed to provide easy and in-depth tutorials on various technologies.I hope it will help you a lot.

- Thulasriam P

Follow Me @Google+
SHARE

    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment