SHARE
TWEET

APCS_CH8_EasyReader.java

calcpage Mar 13th, 2013 32 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.io.InputStreamReader;
  2. import java.io.FileReader;
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.FileNotFoundException;
  6.  
  7. /**
  8.  * @author Gary Litvin
  9.  * @version 1.6, 01/01/11
  10.  *
  11.  * Appendix to:
  12.  *
  13.  * <i>Java Methods: Object-Oriented Programming and Data Structures</i>
  14.  * (Skylight Publishing 2011, ISBN 978-0-9824775-7-1)
  15.  *
  16.  * EasyReader provides simple methods for reading keyboard input and
  17.  * text files.  All exceptions are handled inside the class and are
  18.  * hidden from the user.
  19.  *
  20.    <xmp>
  21.    Example:
  22.    =======
  23.  
  24.        EasyReader kboard = new EasyReader();
  25.        System.out.print("Enter input file name: ");
  26.        String fileName = kboard.readLine();
  27.  
  28.        EasyReader inputFile = new EasyReader(fileName);
  29.        if (inputFile.bad())
  30.        {
  31.          System.err.println("*** Cannot open " + fileName + " ***");
  32.          System.exit(1);
  33.        }
  34.  
  35.        String firstLine = inputFile.readLine();
  36.        if (!inputFile.eof())   // or:  if (firstLine != null)
  37.          System.out.println("The first line is : " + firstLine);
  38.  
  39.        System.out.print("Enter the maximum number of integers to read: ");
  40.        int maxCount = kboard.readInt();
  41.        int count = 0;
  42.  
  43.        while (count < maxCount && !inputFile.eof())
  44.        {
  45.          int k = inputFile.readInt();
  46.          if (!inputFile.eof())
  47.          {
  48.            // process or store this number
  49.            count++;
  50.          }
  51.        }
  52.  
  53.        inputFile.close();    // optional
  54.        System.out.println(count + " numbers read");
  55.  
  56.    </xmp>
  57.  */
  58. public class EasyReader
  59. {
  60.   private String myFileName;
  61.   private BufferedReader myInFile;
  62.   private int myErrorFlags = 0;
  63.   private static final int OPENERROR = 0x0001;
  64.   private static final int CLOSEERROR = 0x0002;
  65.   private static final int READERROR = 0x0004;
  66.   private static final int EOF = 0x0100;
  67.  
  68.   /**
  69.    * Constructs an <code>EasyReader</code> associated with
  70.    * <code>System.in</code>.
  71.    */
  72.   public EasyReader()
  73.   {
  74.     myFileName = null;
  75.     myErrorFlags = 0;
  76.     myInFile = new BufferedReader(
  77.                             new InputStreamReader(System.in), 128);
  78.   }
  79.  
  80.   /**
  81.    * Constructs an <code>EasyReader</code> associated with a file for reading.
  82.    * @param fileName the name or pathname of the file.
  83.    */
  84.   public EasyReader(String fileName)
  85.   {
  86.     myFileName = fileName;
  87.     myErrorFlags = 0;
  88.     try
  89.     {
  90.       myInFile = new BufferedReader(new FileReader(fileName), 1024);
  91.     }
  92.     catch (FileNotFoundException e)
  93.     {
  94.       myErrorFlags |= OPENERROR;
  95.       myFileName = null;
  96.     }
  97.   }
  98.  
  99.   /**
  100.    * Closes the file.
  101.    */
  102.   public void close()
  103.   {
  104.     if (myFileName == null)
  105.       return;
  106.     try
  107.     {
  108.       myInFile.close();
  109.     }
  110.     catch (IOException e)
  111.     {
  112.       System.err.println("Error closing " + myFileName + "\n");
  113.       myErrorFlags |= CLOSEERROR;
  114.     }
  115.   }
  116.  
  117.   /**
  118.    * Checks the status of the file.
  119.    * @return true if an error occurred when opening or reading the file;
  120.    * false otherwise.
  121.    */
  122.   public boolean bad()
  123.   {
  124.     return myErrorFlags != 0;
  125.   }
  126.  
  127.   /**
  128.    * Checks the EOF status of the file.
  129.    * @return true if EOF was encountered in the previous read
  130.    * operation; false otherwise.
  131.    */
  132.   public boolean eof()
  133.   {
  134.     return (myErrorFlags & EOF) != 0;
  135.   }
  136.  
  137.   private boolean ready() throws IOException
  138.   {
  139.     return myFileName == null || myInFile.ready();
  140.   }
  141.  
  142.   /**
  143.    * Reads the next character from the file (any character including
  144.    * a space or a newline character).
  145.    * @return the character read or <code>null</code> character
  146.    * (Unicode 0) if trying to read beyond the EOF.
  147.    */
  148.   public char readChar()
  149.   {
  150.     char ch = '\u0000';
  151.  
  152.     try
  153.     {
  154.       if (ready())
  155.       {
  156.          ch = (char)myInFile.read();
  157.       }
  158.     }
  159.     catch (IOException e)
  160.     {
  161.       if (myFileName != null)
  162.         System.err.println("Error reading " + myFileName + "\n");
  163.       myErrorFlags |= READERROR;
  164.     }
  165.  
  166.     if (ch == '\u0000')
  167.       myErrorFlags |= EOF;
  168.  
  169.     return ch;
  170.   }
  171.  
  172.   /**
  173.    * Reads from the current position in the file up to and including
  174.    * the next newline character.  The newline character is thrown away.
  175.    * @return the string read (excluding the newline character) or
  176.    * null, if trying to read beyond the EOF.
  177.    */
  178.   public String readLine()
  179.   {
  180.     String s = null;
  181.  
  182.     try
  183.     {
  184.       s = myInFile.readLine();
  185.     }
  186.     catch (IOException e)
  187.     {
  188.       if (myFileName != null)
  189.         System.err.println("Error reading " + myFileName + "\n");
  190.       myErrorFlags |= READERROR;
  191.     }
  192.  
  193.     if (s == null)
  194.       myErrorFlags |= EOF;
  195.     return s;
  196.   }
  197.  
  198.   /**
  199.    * Skips whitespace and reads the next word (a contiguous string of
  200.    * non-whitespace characters), up to but excluding the next space,
  201.    * newline, etc.
  202.    * @return the string read or null, if trying to read beyond the EOF.
  203.    */
  204.   public String readWord()
  205.   {
  206.     StringBuffer buffer = new StringBuffer(128);
  207.     char ch = ' ';
  208.     int count = 0;
  209.     String s = null;
  210.  
  211.     try
  212.     {
  213.       while (ready() && Character.isWhitespace(ch))
  214.         ch = (char)myInFile.read();
  215.       while (ready() && !Character.isWhitespace(ch))
  216.       {
  217.         count++;
  218.         buffer.append(ch);
  219.         myInFile.mark(1);
  220.         ch = (char)myInFile.read();
  221.       };
  222.  
  223.       if (count > 0)
  224.       {
  225.         myInFile.reset();
  226.         s = buffer.toString();
  227.       }
  228.       else
  229.       {
  230.         myErrorFlags |= EOF;
  231.       }
  232.     }
  233.  
  234.     catch (IOException e)
  235.     {
  236.       if (myFileName != null)
  237.         System.err.println("Error reading " + myFileName + "\n");
  238.       myErrorFlags |= READERROR;
  239.     }
  240.  
  241.     return s;
  242.   }
  243.  
  244.   /**
  245.    * Reads the next integer (without validating its format).
  246.    * @return the integer read or 0 if, trying to read beyond the EOF,
  247.    * or if the read word does not represent a valid integer.
  248.    */
  249.   public int readInt()
  250.   {
  251.     int result = 0;
  252.     String s = readWord();
  253.  
  254.     if (s != null)
  255.     {
  256.       try
  257.       {
  258.         result = Integer.parseInt(s);
  259.       }
  260.       catch (NumberFormatException ex)
  261.       {
  262.       }
  263.     }
  264.  
  265.     return result;
  266.   }
  267.  
  268.   /**
  269.    * Reads the next double (without validating its format).
  270.    * @return the number read or <code>Double.NaN</code>, if trying to read
  271.    * beyond the EOF, or if the token read does not represent a valid double.
  272.    */
  273.   public double readDouble()
  274.   {
  275.     double result = Double.NaN;
  276.  
  277.     String s = readWord();
  278.     if (s != null)
  279.     {
  280.       try
  281.       {
  282.         result = Double.parseDouble(s);
  283.       }
  284.       catch (NumberFormatException ex)
  285.       {
  286.       }
  287.     }
  288.     return result;
  289.   }
  290. }
RAW Paste Data
Top