001package edu.pdx.cs410J.core;
002
003import java.io.FileWriter;
004import java.io.IOException;
005import java.io.PrintWriter;
006import java.io.Writer;
007
008/**
009 * This program does the same thing as <code>WriteToFile</code> but uses the new
010 * "try with resource" language feature of Java 7.
011 */
012public class WriteToFileTryWithResource {
013
014  /**
015   * The first argument is the file to write to.
016   */
017  public static void main(String[] args) {
018    // Wrap a PrintWriter around System.err
019    PrintWriter err = new PrintWriter(System.err, true);
020
021    try (Writer writer = new FileWriter(args[0])) {
022      // Write the command line arguments to the file
023      for (int i = 1; i < args.length; i++) {
024        writer.write(args[i]);
025        writer.write('\n');
026      }
027    
028      // All done
029      writer.flush();
030      writer.close();
031
032    } catch (IOException ex) {
033      err.println("** " + ex);
034    }
035  }
036}