Create a buffered input stream from the file and reads the bytes back in - Java File Path IO

Java examples for File Path IO:File Stream

Description

Create a buffered input stream from the file and reads the bytes back in

Demo Code

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {
  public static void main(String[] arguments) {
    boolean success = writeStream();
    System.out.println("\nReading: ");
    boolean readSuccess = readStream();
  }/*from  w  w w  .  j  a va 2  s . c om*/
  static boolean writeStream() {
    try (FileOutputStream file = new FileOutputStream("numbers.dat");
        BufferedOutputStream buff = new BufferedOutputStream(file)) {

      for (int out = 0; out <= 200; out++) {
        buff.write(out);
        System.out.print(" " + out);
      }
      buff.close();
      return true;
    } catch (IOException e) {
      System.out.println("Exception: " + e.getMessage());
      return false;
    }
  }

  static boolean readStream() {
    try (FileInputStream file = new FileInputStream("numbers.dat");
        BufferedInputStream buff = new BufferedInputStream(file)) {
      int in;
      do {
        in = buff.read();
        if (in != -1)
          System.out.print(" " + in);
      } while (in != -1);
      buff.close();
      return true;
    } catch (IOException e) {
      System.out.println("Exception: " + e.getMessage());
      return false;
    }
  }
}

Result


Related Tutorials