ReadTextFile.java

c:\ece538\ch15\TextFileApps> java ReadTextFile
Account  First Name  Last Name      Balance
100      Bob         Blue             24.98
200      Steve       Green          -345.67
300      Pam         White             0.00
400      Sam         Red             -42.16
500      Sue         Yellow          224.62


ReadTextFile.java

// Fig. 15.6: ReadTextFile.java
// This program reads a text file and displays each record.
import java.io.IOException;
import java.lang.IllegalStateException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class ReadTextFile
{
   private static Scanner input;

   public static void main(String[] args)
   {
      String filename = "clients.txt";
      if (args.length>0) filename = args[0];
      openFile(filename);
      readRecords();
      closeFile();
   } 

   // open file clients.txt
   public static void openFile(String filename)
   {
      try
      {
         input = new Scanner(Paths.get(filename)); 
      } 
      catch (IOException ioException)
      {
         System.err.println("Error opening file. Terminating.");
         System.exit(1);
      } 
   }

   // read record from file
   public static void readRecords()
   {
      System.out.printf("%-10s%-12s%-12s%10s%n", "Account",
         "First Name", "Last Name", "Balance");

      try 
      {
         while (input.hasNext()) // while there is more to read
         {
            // display record contents                     
            System.out.printf("%-10d%-12s%-12s%10.2f%n", input.nextInt(), 
               input.next(), input.next(), input.nextDouble());
         }
      } 
      catch (NoSuchElementException elementException)
      {
         System.err.println("File improperly formed. Terminating.");
      } 
      catch (IllegalStateException stateException)
      {
         System.err.println("Error reading from file. Terminating.");
      } 
   } // end method readRecords

   // close file and terminate application
   public static void closeFile()
   {
      if (input != null)
         input.close();
   } 
} // end class ReadTextFile


Maintained by John Loomis, updated Fri Jan 31 13:26:50 2020