写入二进制流
import java.io.BufferedOutputStream; import java.io.DataOutputStream; import java.io.File; /** 来 自 nowjava.com **/ import java.io.FileOutputStream; import java.io.IOException; public class WriteBinaryFile { public static void main(String[] args) { Movie[] movies = getMovies(); DataOutputStream out = openOutputStream("movies.dat"); for (Movie m : movies) writeMovie(m, out); closeFile(out); } /* from N o w J a v a . c o m */ 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); } } }