集册 Java实例教程 从数据输入流读取

从数据输入流读取

欢马劈雪     最近更新时间:2020-01-02 10:19:05

507
从数据输入流读取

import java.io.BufferedInputStream;

import java.io.DataInputStream;
/**
来 自 NowJava.com - 时代Java
**/

import java.io.EOFException;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.text.NumberFormat;


public class ReadBinaryFile {

  public static void main(String[] args) {

    NumberFormat cf = NumberFormat.getCurrencyInstance();


    DataInputStream in = getStream("movies.dat");


    boolean eof = false;

    while (!eof) {

      Movie movie = readMovie(in);

      if (movie == null)//n o w  j a v a  . c o m 提供

        eof = true;

      else {

        String msg = Integer.toString(movie.year);

        msg += ": " + movie.title;

        msg += " (" + cf.format(movie.price) + ")";

        System.out.println(msg);

      }

    }

    closeFile(in);

  }


  private static DataInputStream getStream(String name) {

    DataInputStream in = null;

    try {

      File file = new File(name);

      in = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));

    } catch (FileNotFoundException e) {

      System.out.println("The file doesn't exist.");

      System.exit(0);

    } catch (IOException e) {

      System.out.println("I/O Error creating file.");

      System.exit(0);

    }

    return in;

  }


  private static Movie readMovie(DataInputStream in) {

    String title = "";

    int year = 0;

    ;

    double price = 0.0;

    ;


    try {

      title = in.readUTF();

      year = in.readInt();

      price = in.readDouble();

    } catch (EOFException e) {

      return null;

    } catch (IOException e) {

      System.out.println("I/O Error reading file.");

      System.exit(0);

    }

    return new Movie(title, year, price);


  }


  private static void closeFile(DataInputStream in) {

    try {

      in.close();

    } catch (IOException e) {

      System.out.println(
展开阅读全文