集册 Java实例教程 从文本文件中读取

从文本文件中读取

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

557
从文本文件读取

import java.io.BufferedReader;//来 自 时 代 J a v a

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import java.text.NumberFormat;


public class ReadFile {

  public static void main(String[] args) {

    NumberFormat cf = NumberFormat.getCurrencyInstance();


    BufferedReader in = getReader("movies.txt");


    Movie movie = readMovie(in);
    /**
    来 自 N o w J a v a . c o m
    **/

    while (movie != null) {

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

      msg += ": " + movie.title;

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

      System.out.println(msg);

      movie = readMovie(in);

    }

  }


  private static BufferedReader getReader(String name) {

    BufferedReader in = null;

    try {

      File file = new File(name);

      in = new BufferedReader(new FileReader(file));

    } catch (FileNotFoundException e) {

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

      System.exit(0);

    } catch (IOException e) {

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

      System.exit(0);

    }

    return in;

  }


  private static Movie readMovie(BufferedReader in) {

    String title;

    int year;

    double price;

    String line = "";

    String[] data;


    try {

      line = in.readLine();

    } catch (IOException e) {

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

      System.exit(0);

    }


    if (line == null)

      return null;

    else {

      data = line.split("\t");

      title = data[0];

      year = Integer.parseInt(data[1]);

      price = Double.parseDouble(data[2]);

      return new Movie(title, year, price);

    }

  }


}


展开阅读全文