Writing to a Binary File : Buffer Stream « File Input Output « Java






Writing to a Binary File

 

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;

public class WriteBinaryFile {
  public static void main(String[] args) throws Exception {
    Product[] movies = new Product[10];

    movies[0] = new Product("W", 1946, 14.95);
    movies[1] = new Product("T", 1965, 12.95);
    movies[2] = new Product("Y", 1974, 16.95);
    movies[3] = new Product("R", 1975, 11.95);
    movies[4] = new Product("S", 1977, 17.95);
    movies[5] = new Product("P", 1987, 16.95);
    movies[6] = new Product("G", 1989, 14.95);
    movies[7] = new Product("A", 1995, 19.95);
    movies[8] = new Product("Game", 1997, 14.95);
    movies[9] = new Product("F", 2001, 19.95);

    DataOutputStream out = openOutputStream("movies.dat");
    for (Product m : movies)
      writeMovie(m, out);
    out.close();
  }

  private static DataOutputStream openOutputStream(String name) throws Exception {
    DataOutputStream out = null;
    File file = new File(name);
    out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
    return out;
  }

  private static void writeMovie(Product m, DataOutputStream out) throws Exception {
    out.writeUTF(m.title);
    out.writeInt(m.year);
    out.writeDouble(m.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.Reading from a Binary File with BufferedInputStream