Introduction
In this tutorial, we will learn how to convert InputStream to String in Java.
Example
import java.io.InputStream; import java.net.URL; public class InputStreamToString { public static void main(String[] args) { //very frequent asked question in interview , regarding closable interface try(InputStream inputStream = new URL("https://www.oracle.com/index.html").openStream()){ System.out.println(convertToString(inputStream)); }catch (Exception e) { // TODO: handle exception } } private static String convertToString(InputStream inputStream) throws Exception{ return new String(inputStream.readAllBytes()); } }
Conclusion
Above example is the simplest method to convert an Inpustream to String in Java. There are alternate solutions available like using commonio jar and converting InputStream to ByteStream etc.Hope you enjoy this tutorial. Happy learning
Comments
Post a Comment