Reading from a Binary File with BufferedInputStream : Buffer Stream « File Input Output « Java






Reading from a Binary File with BufferedInputStream

 

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.NumberFormat;

public class ReadBinaryFile {
  public static void main(String[] args) throws Exception{
    NumberFormat cf = NumberFormat.getCurrencyInstance();

    File file = new File("product.dat");
    DataInputStream  in = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));

    boolean eof = false;
    while (!eof) {
      Product movie = readMovie(in);
      if (movie == null)
        eof = true;
      else {
        String msg = Integer.toString(movie.year);
        msg += ": " + movie.title;
        msg += " (" + cf.format(movie.price) + ")";
        System.out.println(msg);
      }
    }
    in.close();
  }

  private static Product readMovie(DataInputStream in) {
    String title = "";
    int year = 0;
    double price = 0.0;

    try {
      title = in.readUTF();
      year = in.readInt();
      price = in.readDouble();
    } catch (EOFException e) {
      return null;
    } catch (IOException e) {
      System.out.println("I/O Error");
      System.exit(0);
    }
    return new Product(title, year, price);
  }
}

class Product {
  public String title;

  public int year;

  public double price;

  public Product(String title, int year, double price) {
    this.title = title;
    this.year = year;
    this.price = price;
  }
}

 








Related examples in the same category

1.Use BufferedInputStream and BufferedOutputStream to copy byte array
2.Use buffered input.
3.Writing to a Binary File