Writing to a binary stream - Java File Path IO

Java examples for File Path IO:File Stream

Description

Writing to a binary stream

Demo Code

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

public class WriteBinaryFile {
  public static void main(String[] args) {
    Movie[] movies = getMovies();/*w  w w  . ja v  a 2s  . com*/
    DataOutputStream out = openOutputStream("movies.dat");
    for (Movie m : movies)
      writeMovie(m, out);
    closeFile(out);
  }

  private static Movie[] getMovies() {
    Movie[] movies = new Movie[10];
    movies[0] = new Movie("It's a Wonderful Life", 1946, 14.95);
    movies[1] = new Movie("Star Wars", 1977, 17.95);
    movies[2] = new Movie("Star Wars 7", 2018, 17.95);
    return movies;
  }

  private static DataOutputStream openOutputStream(String name) {
    DataOutputStream out = null;
    try {
      File file = new File(name);
      out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
      return out;
    } catch (IOException e) {
      System.out.println("I/O Exception opening file.");
      System.exit(0);
    }
    return out;
  }

  private static void writeMovie(Movie m, DataOutputStream out) {
    try {
      out.writeUTF(m.title);
      out.writeInt(m.year);
      out.writeDouble(m.price);
    } catch (IOException e) {
      System.out.println("I/O Exception writing data.");
      System.exit(0);
    }
  }

  private static void closeFile(DataOutputStream out) {
    try {
      out.close();
    } catch (IOException e) {
      System.out.println("I/O Exception closing file.");
      System.exit(0);
    }
  }

}
class Movie {
  public String title;
  public int year;
  public double price;

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

Related Tutorials