Writing Character Streams - Java File Path IO

Java examples for File Path IO:Text File

Introduction

FileWriter class connects to a File object with only basic writing ability.

BufferedWriter connects to a FileWriter and provides output buffering.

PrintWriter class connects to a Writer, which can be a BufferedWriter, a FileWriter, or any other object that extends the abstract Writer class.

The following code connects a PrintWriter to a text file.

Demo Code

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

public class Main {
  public static void main(String[] args) {
    Movie[] movies = getMovies();//  w  w  w.jav a  2  s  .  co  m

    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);
    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 title;
  public int year;
  public double price;

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

Related Tutorials