Powered by Blogger.

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
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt utlaoreet dolore.