Monday, 2 May 2016

How to convert InputStream to String using Java native library

How to convert java.io.InputStream to String using Java native library

In the previous article i showed How to convert java.io.InputStream to String using Apache IOUtils.
In this article we see how to convert inputstream to string in java using stanard java library.

For Example:
Say we have a file called D:/sample.txt. We will create an java.io.InputStream to show this example.

How to convert java InputStream to String


File: InputStreamToStringExample.java

import java.io.*;
import java.util.Scanner;

public class InputStreamToStringExample {

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

  InputStream inputStream = new FileInputStream("D:\\sample.txt");
  Scanner s = new Scanner(inputStream).useDelimiter("\\A");
  String text= s.hasNext() ? s.next() : "";
  
  System.out.println(text);
      
  s.close();
  inputStream.close();
 }
}



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.