/* * T03n02.java -- Use PrintWriter to create a text file. PrintWriter * objects support print() and println() methods, and they work just * like System.out.print() and System.out.println() do for screen output. * (Probably not a big coincidence!) * * Only constructors in PrintWriter throw checked exceptions, so only * their invocations need to be in try blocks. * * The next example will show how to read a text file. */ import java.io.*; public class T03n02 { public static void main (String [] args) { final String fileName = "T03n02.out"; PrintWriter textStream = null; System.out.println("Writing some text to the file '" + fileName + "'..."); try { textStream = new PrintWriter(fileName); } catch (IOException e) { System.out.println("I/O ERROR: Something went wrong with the " + "creation of the text file.\nHere's what " + "I can tell you:"); System.out.println(" The Error: " + e.getClass().getName()); String mesg = e.getMessage(); if (mesg == null) { System.out.println("The message: None."); } else { System.out.println("The message: " + mesg); } System.out.println("The stack trace:"); e.printStackTrace(); } textStream.println("Programming today is a race between " + "software engineers striving to build"); textStream.println("bigger and better idiot-proof programs, " + "and the universe trying to produce"); textStream.println("bigger and better idiots. So far, the " + "Universe is winning. --- Rich Cook"); textStream.close(); // Closing streams is a good habit to acquire System.out.println("Done!"); } }