Java file I/O

Java provides a number of classes and methods that allow to read and write files. In Java all files are byte-oriented. Two of the most often-used stream classes are FileInputStream and FileOutputStream, which create byte streams linked to files.

  1. To open a file, simple create an object of one of the classes specifying the name of the file as an argument to the constructor.
  2. Use close() to close the file


FileInputStream (String fileName)
FileOutputStream (String fileName)

fileName specifies the name of the file that you want to open. After completing your file operations, you should close it by calling close(). It is defined by both FileInputStream and FileInputStream , as shown here:

void close() throws IOException

To read from a file, you can use a version of read() that is defined within FileInputStream, as shown here:

void close() throws IOException

Example of File Reading Code:


class Variables
   public static void main(String[] args) throws IOException {
   int i;

   FileInputStream fin;
   File file = new File("/home/linuxjunky/Documents/Protein1");    

   try {
       fin=new FileInputStream(file);
   } catch (FileNotFoundException e) {
       System.out.println("File Not Found");
   } catch (ArrayIndexOutOfBoundsException e) {
       System.out.println("Out of Bounds");
   int j = 0;

   int L = (int) file.length();
   char[] Array = new char[L];
   System.out.println("Th Length of The Protein Is: " + L);
       i =;

       if (i != -1)
           Array[j] = (char) i;
   } while(i != -1);