Java - File Input Output Byte Read

Introduction

The following code uses FileInputStream to read byte from a file.

It uses the try-resource syntax to manage to close FileInputStream.

Two types of exceptions are listed in the catch statements.

Demo

import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Main {
  public static void main(String[] args) {
    String dataSourceFile = "Main.java";
    try (FileInputStream fin = new FileInputStream(dataSourceFile)) {
      byte byteData;
      while ((byteData = (byte) fin.read()) != -1) {
        System.out.print((char) byteData);
      }//ww w . j  av  a  2  s  .co m
    } catch (FileNotFoundException e) {
      FileUtil.printFileNotFoundMsg(dataSourceFile);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

class FileUtil {
  // Prints the location details of a file
  public static void printFileNotFoundMsg(String fileName) {
    String workingDir = System.getProperty("user.dir");
    System.out.println("Could not find the file '" + fileName + "' in '"
        + workingDir + "' directory ");
  }

  // Closes a Closeable resource such as an input/output stream
  public static void close(Closeable resource) {
    if (resource != null) {
      try {
        resource.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

Result