Monday, 2 May 2016

How to convert java.io.InputStream to String

How to convert java InputStream to String

How to convert java.io.InputStream to String

While working on Files and FTP we come across some situations where we need to convert a java.io.InputStream to String. This can be easily achieved by using various techniques. Some of them are given below.


This example uses Apache IOUtils which can be downloaded from http://mvnrepository.com/artifact/commons-io/commons-io/2.5
To see How to convert InputStream to String using standard Java library CLICK HERE.


Suppose we have a file in D:/sample.txt
How to convert java InputStream to String



Method 1:

File: InputStreamToStringExample.java

import java.io.*;
import org.apache.commons.io.IOUtils;

public class InputStreamToStringExample {

 public static void main(String[] args) throws IOException {

  InputStream inputStream = new FileInputStream("D:\\sample.txt");
  String result = IOUtils.toString(inputStream, "UTF-8");
  System.out.println(result);
  
  IOUtils.closeQuietly(inputStream);
 }
}



Method 2:

File: InputStreamToStringExample.java

import java.io.*;
import org.apache.commons.io.IOUtils;

public class InputStreamToStringExample {

 public static void main(String[] args) throws IOException {

  InputStream inputStream = new FileInputStream("D:\\sample.txt");
  StringWriter stringWriter = new StringWriter();
  IOUtils.copy(inputStream, stringWriter, "UTF-8");
  
  String text = stringWriter.toString();
  System.out.println(text);
 }
}


Output:
This is an example.

No comments:

Post a Comment

Coder Magnet
CoderMagnet is full of resources from our daily development activities. It has solutions for common problematic scenarios in technologies like Java 8, AEM, JCR and also occasionally gives you tips on Blogger as well.