Source of FileWriteChars.java


  1: //FileWriteChars.java

  3: import java.util.Scanner;
  4: import java.io.FileWriter;
  5: import java.io.IOException;

  7: public class FileWriteChars
  8: {
  9:     /* Method closes a FileWriter.
 10:        Prints exception message if closing fails.
 11:      */
 12:     public static void closeFileWriter(FileWriter fileWriter)
 13:     {
 14:         try
 15:         {
 16:             // Ensure fileWriter references a valid object
 17:             if (fileWriter != null)
 18:             {
 19:                 System.out.println("Closing file.");
 20:                 fileWriter.close(); // close() may throw IOException if fails
 21:             }
 22:         }
 23:         catch (IOException closeExcpt)
 24:         {
 25:             System.out.println
 26:             (
 27:                 "Error closing file: "
 28:                 + closeExcpt.getMessage()
 29:             );
 30:         }
 31:     }

 33:     public static void main(String[] args)
 34:     {
 35:         Scanner scnr = new Scanner(System.in);
 36:         final int NUM_CHARS_TO_WRITE = 10; // Num chars to write to file
 37:         int countVar; // Track num chars written so far
 38:         FileWriter fileWriter = null; // FileWriter for writing file
 39:         String fileName; // User defined file name
 40:         char charWrite;  // Char data written to file

 42:         countVar = 0;
 43:         charWrite = 'a';

 45:         // Get file name from user
 46:         System.out.print("Enter a valid file name: ");
 47:         fileName = scnr.next();

 49:         try
 50:         {
 51:             System.out.println("Creating file " + fileName + ".");
 52:             fileWriter = new FileWriter(fileName); // May throw IOException

 54:             // Use file output stream
 55:             System.out.print
 56:             (
 57:                 "Writing " + NUM_CHARS_TO_WRITE
 58:                 + " characters: "
 59:             );
 60:             while (countVar < NUM_CHARS_TO_WRITE)
 61:             {
 62:                 fileWriter.write(charWrite);
 63:                 System.out.print(charWrite);

 65:                 charWrite++; // Get next char ready
 66:                 countVar++;  // Keep track of number chars written
 67:             }
 68:             System.out.println();
 69:         }
 70:         catch (IOException excpt)
 71:         {
 72:             System.out.println("Caught IOException: " + excpt.getMessage());
 73:         }
 74:         finally
 75:         {
 76:             closeFileWriter(fileWriter); // Ensure file is closed!
 77:         }
 78:     }
 79: }