Home Tutorial Java Core Files How to convert Input Stream to String in java

 
 

Share on Google+Share on Google+
How to convert Input Stream to String in java
Posted on: February 16, 2005 at 12:00 AM
Advertisement
In this section, you will learn how to convert InputStream into string.

How to convert Input Stream to String in java

The InputStream class is the base class of all input streams in the Java IO API. It is used for reading byte based data, one byte at a time. In this section, you will learn how to convert InputStream into string. 

Description of code:

Since class InputStream is super class of the FileInputStream so we can store file into InputStream by taking the file through FileInputStream. The read() method of an InputStream class contains the byte value and returns an int. If the read() method returns -1, there is no more data to read in the stream. This value is stored into the StringBuffer as a  string which will then converted into string.

Here is the code:

import java.io.*;

public class ConvertInputStreamToString {
  public static void main(String[] argsthrows IOException {
    InputStream is = new FileInputStream("C:/file.txt");
    StringBuffer buffer = new StringBuffer();
    byte[] b = new byte[4096];
    for (int n; (n = is.read(b)) != -1;) {
      buffer.append(new String(b, 0, n));
    }
    String str = buffer.toString();
    System.out.println(str);
  }
}
Advertisement

Related Tags for How to convert Input Stream to String in java:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: February 16, 2005

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com