Java I/O How to - Create Stream from a String/Byte Array








Question

We would like to know how to create Stream from a String/Byte Array.

Answer

//from  www. j a v  a2  s .  c  om
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;

public class Main {
  public static void main(String[] args) throws Exception {

    DataInputStream in3 = new DataInputStream(new ByteArrayInputStream(
        "a dbcde".getBytes()));
    System.out.print((char) in3.readByte());
    in3.close();
  }
}

The code above generates the following result.

Convert InputStream to String

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
/*  w  w w. ja  v  a  2  s  .c o  m*/
public class Main {

  public static void main(String[] args) throws Exception {
    InputStream is = Main.class.getResourceAsStream("/data.txt");
    System.out.println(convertStreamToString(is));
  }

  public static String convertStreamToString(InputStream is) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      sb.append(line + "\n");
    }
    is.close();
    return sb.toString();
  }
}