集册 Java实例教程 编写字符流

编写字符流

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

469
FileWriter类仅具有基本的编写功能才能连接到File对象。

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileWriter;//来 自 N  o w  J a v a . c o m

import java.io.IOException;

import java.io.PrintWriter;


public class Main {

  public static void main(String[] args) {

    Movie[] movies = getMovies();


    PrintWriter out = openWriter("movies.txt");

    for (Movie m : movies)

      writeMovie(m, out);

    out.close();

  }


  private static Movie[] getMovies() {

    Movie[] movies = new Movie[10];


    movies[0] = new Movie("It's a Wonderful Life", 1946, 14.95);/**from 时 代 J     a    v  a - nowjava.com**/

    movies[1] = new Movie("Star Wars", 1977, 17.95);

    movies[2] = new Movie("Star Wars 7", 2018, 17.95);


    return movies;

  }


  private static PrintWriter openWriter(String name) {

    try {

      File file = new File(name);

      PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)), true); // flush

      return out;

    } catch (IOException e) {

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

      return null;

    }

  }


  private static void writeMovie(Movie m, PrintWriter out) {

    String line = m.title;

    line += "\t" + Integer.toString(m.year);

    line += "\t" + Double.toString(m.price);

    out.println(line);

  }



}

class Movie {

  public String ti
展开阅读全文