How do I convert an InputStream to a String in Java?
Asked Answered
R

6

24

Suppose I have an InputStream that contains text data, and I want to convert this to a String (for example, so I can write the contents of the stream to a log file).

What is the easiest way to take the InputStream and convert it to a String?

public String convertStreamToString(InputStream is) { 
    // ???
}
Rutger answered 19/11, 2009 at 14:47 Comment(2)
possible duplicate of In Java how do a read an input stream in to a string?Clonus
Agree. I've voted to close this as duplicate and edited the other question to include some of the title keywords and question text from here.Rutger
P
22

This is my version,

public static String readString(InputStream inputStream) throws IOException {

    ByteArrayOutputStream into = new ByteArrayOutputStream();
    byte[] buf = new byte[4096];
    for (int n; 0 < (n = inputStream.read(buf));) {
        into.write(buf, 0, n);
    }
    into.close();
    return new String(into.toByteArray(), "UTF-8"); // Or whatever encoding
}
Philipines answered 19/11, 2009 at 14:55 Comment(0)
P
24

If you want to do it simply and reliably, I suggest using the Apache Jakarta Commons IO library IOUtils.toString(java.io.InputStream, java.lang.String) method.

Puentes answered 19/11, 2009 at 14:53 Comment(3)
This is the short and sweet way.Intermarriage
The only downside to this is that you need to take an external dependency in this library, which may not always be desired.Rutger
You need to specify the encoding too, otherwise it will use the platform default, which is anything but reliable.Swoop
P
22

This is my version,

public static String readString(InputStream inputStream) throws IOException {

    ByteArrayOutputStream into = new ByteArrayOutputStream();
    byte[] buf = new byte[4096];
    for (int n; 0 < (n = inputStream.read(buf));) {
        into.write(buf, 0, n);
    }
    into.close();
    return new String(into.toByteArray(), "UTF-8"); // Or whatever encoding
}
Philipines answered 19/11, 2009 at 14:55 Comment(0)
G
11
String text = new Scanner(inputStream).useDelimiter("\\A").next();

The only tricky is to remember the regex \A, which matches the beginning of input. This effectively tells Scanner to tokenize the entire stream, from beginning to (illogical) next beginning...
- from the Oracle Blog

Glabrescent answered 17/7, 2010 at 13:14 Comment(0)
P
3

Since Java 9 InputStream.readAllBytes() even shorter:

String toString(InputStream inputStream) throws IOException {
   return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8); // Or whatever encoding
}

Note: InputStream is not closed in this example.

Pungy answered 29/4, 2020 at 16:40 Comment(0)
R
1

You can use a BufferedReader to read the stream into a StringBuilder in a loop, and then get the full contents from the StringBuilder:

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(); 
} 

Full disclosure: This is a solution I found on KodeJava.org. I am posting it here for comments and critique.

Rutger answered 19/11, 2009 at 14:47 Comment(3)
Keep in mind that the BufferedReader constructor you're using assumes the platform default text encoding on the bytes coming from the InputStream, which will probably be wrong. You must know the encoding and specify it in the Reader constructor.Load
By using this constructor, you tell the InputStreamReader to use the default platform encoding, wich should be avoided. You should specify the charset the data is encoded in so it gets correctly decoded using one of the other three constructors.Ciliate
It's also unnecessary effort to use a BufferedReader to split the input on line breaks, just to add the line breaks manually to the StringBuilder and almost a WTF to actually use a StringBuilder to prevent String object creation, but then call append(line + "\n") instead of append(line).append("\n"). Closing the InputStream is also not particularly clever.Ascribe
T
0

A nice way to do this is using Apache commons IOUtils

IOUtils.toString(inputStream, string);
Terceira answered 21/12, 2019 at 15:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.