How to convert InputStream to a string in Java?


Suppose I have a have java.io.InputStream object, how should I process that object and produce a String from it in java?

I would need a function which reads InputStream and output it as a String

thanks


Asked by:- pika
0
: 350 At:- 11/15/2017 8:03:52 AM
java InputStream java.io string






1 Answers
profileImage Answered by:- jaiprakash

These are few ways to do it

1. Using InputStreamReader : simple implementation which uses the InputStreamReader to convert from bytes to characters.

private static String inputStreamToString(InputStream in)
    throws java.io.IOException
{
    BufferedReader br = null;
    try {
    InputStreamReader isr = new InputStreamReader(in);
    br = new BufferedReader(isr);
    char cbuf[] = new char[2048];
    int len;
    StringBuilder sbuf = new StringBuilder();
    while ((len = br.read(cbuf, 0, cbuf.length)) != -1)
        sbuf.append(cbuf, 0, len);
    return sbuf.toString();
    } finally {
    if ( br != null ) br.close();
    }
}

2. Using Apache commons IOUtils to copy to copy the InputStream into a StringWriter

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();

3. using only standard Java library

static String convertStreamToString(java.io.InputStream is) {
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

4. Using parallel Stream Api (Java 8). Warning: This solution convert different line breaks (like \r\n) to \n

    String result = new BufferedReader(new InputStreamReader(inputStream)).lines()
       .parallel().collect(Collectors.joining("\n"));

5. Complete Example :

public static void main(String[] args) throws FileNotFoundException, IOException {
 
        InputStream in = new ByteArrayInputStream("hello".getBytes());
 
        BufferedReader reader = new BufferedReader(new InputStreamReader( in ));
 
        String line = null;
        StringBuilder out = new StringBuilder();
 
        while ((line = reader.readLine()) != null) {
            out.append(line);
        }
 
        System.out.println(out.toString());
        reader.close();
 
    }

//output :hello

there are many more other ways, but i have listed mostly used one's, but it all depends on your requirement and your choice

 

0
At:- 11/20/2017 7:01:37 AM





Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use