import java.io.*;

public class FileReader implements InChannel<Integer> {

  /**
   * True if the channel still holds data to be read.
   */
  private int nextData = 0;

  /**
   * The file from where data will be read.
   */
  private FileInputStream srcFile;

  /**
   * Constructor.
   *
   * @param fileName
   *        the name of the input file.
   * @throws FileNotFoundException
   *         In case we fail to open the file.
   */
  public FileReader(final String fileName) throws FileNotFoundException {
    srcFile = new FileInputStream(new File(fileName));
    try {
      nextData = srcFile.read();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * Write the data into the file.
   * @return the value just read.
   * @throws IOException
   *         In case we fail to write the data.
   */
  public final Integer read() throws IOException {
    if (hasData()) {
      int i = nextData;
      nextData = srcFile.read();
      return i;
    } else {
      throw new IOException("Trying to read empty input channel.");
    }
  }

  /**
   * Is true if there is more data to be read, and it is false if the last
   * data has been read.
   * @return a boolean value.
   */
  public final boolean hasData() {
    return nextData != -1;
  }

  @Override
  public final void finalize() {
    try {
      srcFile.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
