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 writes the arguments from the command line to a text 010 * file. It demonstrates the <code>FileWriter</code> class. 011 */ 012public class WriteToFileUsingTryWithResources { 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 023 // Write the command line arguments to the file 024 for (int i = 1; i < args.length; i++) { 025 writer.write(args[i]); 026 writer.write('\n'); 027 } 028 029 // All done 030 writer.flush(); 031 032 } catch (IOException ex) { 033 err.println("** " + ex); 034 } 035 } 036}