Writing to a Text File : Buffered Reader Writer « File Input Output « Java






Writing to a Text File

  


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class WriteFile {
  public static void main(String[] args) {
    Product[] movies = new Product[10];

    movies[0] = new Product("L", 1946, 14.95);
    movies[1] = new Product("T", 1965, 12.95);
    movies[2] = new Product("Y", 1974, 16.95);
    movies[3] = new Product("T", 1975, 11.95);
    movies[4] = new Product("S", 1977, 17.95);
    movies[5] = new Product("B", 1987, 16.95);
    movies[6] = new Product("G", 1989, 14.95);
    movies[7] = new Product("A", 1995, 19.95);
    movies[8] = new Product("G", 1997, 14.95);
    movies[9] = new Product("R", 2001, 19.95);

    PrintWriter out = openWriter("movies.txt");
    for (Product m : movies)
      writeMovie(m, out);
    out.close();
  }

  private static PrintWriter openWriter(String name) {
    try {
      File file = new File(name);
      PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)), true);
      return out;
    } catch (IOException e) {
      System.out.println("I/O Error");
      System.exit(0);
    }
    return null;
  }

  private static void writeMovie(Product m, PrintWriter out) {
    String line = m.title;
    line += "\t" + Integer.toString(m.year);
    line += "\t" + Double.toString(m.price);
    out.println(line);
  }


}
class Product {
  public String title;

  public int year;

  public double price;

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

   
  








Related examples in the same category

1.Use a BufferedReader to read characters from the console.
2.Read a string from console using a BufferedReader.
3.Creates a tiny text editor with BufferedReader
4.how to read lines from a file and print these to the standard output stream
5.Fast BufferedWriter