Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
3 views
in Java by (20.3k points)

If you have a 

java.io.InputStream 

object, how should you process that object and produce a String?

Suppose I have an InputStream that contains text data, and I want to convert it to a String, so for example I can write that to a log file.

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

public String convertStreamToString(InputStream is) {

    // ???

}

2 Answers

+1 vote
by (40.7k points)

There are several ways to convert an InputStream into a String in Java. I’ll list out a few ways to do this:

      1. 

  import java.utill.scanner;

This provides an easier way to convert InputStream into String in Java.

public String convert ( InputStream is, Charset ch) throws IOException {

try (Scanner sc = new Scanner(is, ch.name())) {

return sc.applyDelimiter("$\A1").next();

 }

}

 

     2.  <!--[endif]-->Another way to do this by using Stream API

    In this Java Stream’s API is used to convert InputStream to String.

public String convert (InputStream is, Charset ch) throws IOException {

try (BufferedReader br1 = new BufferedReader(new InputStreamReader(is, ch))) {

return br1.lines().collect(Collectors.joining(System.lineSeparator()));

 }

}

0 votes
by (106k points)

To read and convert the object into String type you can also use Java Standard Library. Below is the code for the same:-

static String convertStreamToString(java.io.InputStream is) {

    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");

    return s.hasNext() ? s.next() : "";

}

Related questions

Browse Categories

...