Source Code : Writing to a Binary File

Java Is Open Source Programming Language You Can Download From Java and Java Libraries From http://www.oracle.com. Click Here to download
We provide this code related to title for you to solve your developing problem easily. Libraries which is import in this program you can download from http://www.oracle.com. Click Here or search from google with Libraries Name you get jar file related it

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;
  }
}

 

Thank with us