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

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JavaFX
25.JDK 6
26.JDK 7
27.JNDI LDAP
28.JPA
29.JSP
30.JSTL
31.Language Basics
32.Network Protocol
33.PDF RTF
34.Reflection
35.Regular Expressions
36.Scripting
37.Security
38.Servlets
39.Spring
40.Swing Components
41.Swing JFC
42.SWT JFace Eclipse
43.Threads
44.Tiny Application
45.Velocity
46.Web Services SOA
47.XML
Java » File Input Output » Buffer Stream 




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[] argsthrows Exception {
    Product[] movies = new Product[10];

    movies[0new Product("W"194614.95);
    movies[1new Product("T"196512.95);
    movies[2new Product("Y"197416.95);
    movies[3new Product("R"197511.95);
    movies[4new Product("S"197717.95);
    movies[5new Product("P"198716.95);
    movies[6new Product("G"198914.95);
    movies[7new Product("A"199519.95);
    movies[8new Product("Game"199714.95);
    movies[9new Product("F"200119.95);

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

  private static DataOutputStream openOutputStream(String namethrows 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 outthrows 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
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.