Reading from a Binary File with BufferedInputStream

来源:互联网 发布:女生旅游攻略 知乎 编辑:程序博客网 时间:2024/03/29 20:50
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;  }}