The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist who works with traditional aesthetic and literary forms as
well as mathematical concepts, to communicate the way that an algorithm works and to convince a reader that the results will be correct. Donald E. Knuth

File Handling

Files are a means to store data in a storage device. Java file handling provides a mechanism to store output of a program in a file and read from a file on the disk. The java.io package contains a class called File which provides support for file creation, deletion and manipulation operations. Now, we will discuss different mechanisms to read and write files in Java.

FileInputStream and FileOutputStream classes
We can instantiate an object of FileInputStream class and use it to read specified bytes of data stored in a file. Similarly, FileOutputStream is used to write bytes to a file. Following programs illustrate the use of these two classes to read / write files :

Program to write a file 'str.txt' in memory
import java.io.*;
public class FileOutputStreamDemo {
   public static void main(String args[]) {
      byte str[] = { 'T','h','i','s',' ','i','s',' ',
                  'c','s','e','g','e','e','k','.','c','o','m' };
      try {
         // create an output file stream and connect it to file str.txt
         FileOutputStream ofile = new FileOutputStream("str.txt");
         ofile.write(str); // write data to the stream
         ofile.close(); //close the stream
         System.out.println("Data written to the file ...");
      } catch(Exception e) {
         System.out.println(e);
      }
   }
}
Run this program in your system to write to a file  
Program to read the file 'str.txt' created by the previous program
import java.io.*;
public class FileInputStreamDemo {
   public static void main(String args[]) {
      try {
         // create an input file stream and connect it to file str.txt
         FileInputStream ifile = new FileInputStream("str.txt");
         int x;
         // read the file character by character
         while((x = ifile.read()) != -1) {
            System.out.print((char)x);
         }
         System.out.println();
         ifile.close(); // close the stream
      } catch(Exception e) {
         System.out.println(e);
      }
   }
}
Run this program in your system to read from a file  


FileReader and FileWriter classes
If we want to deal with textual information in a file, then it is better to use FileReader and FileWriter classes which are designed to read and write character-oriented data. Following program illustrates the use of these classes :

Program to write a file 'data.txt' in memory
import java.io.*;
public class FileWriterDemo {
   public static void main(String args[]) {
      String str = "I am learning Java";
      try {
         File ofile = new File("data.txt");
         FileWriter fw = new FileWriter(ofile);
         /* the above statements to open a file can be reaplaced by
          * the following statement.
          * FileWriter fw = new FileWriter("data.txt");
          */
         fw.write(str);
         fw.close();
         System.out.println("Data written to the file");
      } catch(Exception e) {
         System.out.println(e);
      }
   }
}
Run this program in your system to write to a file  
Program to read the file 'data.txt' created by the previous program
import java.io.*;
public class FileReaderDemo {
   public static void main(String args[]) {
      try {
         FileReader fr = new FileReader("data.txt");
         int x;
         while((x = fr.read()) != -1) {
            System.out.print((char)x);
         }
         System.out.println();
         fr.close();
      } catch(Exception e) {
         System.out.println(e);
      }
   }
}
Run this program in your system to read from a file  


CharArrayWriter class
This class is used to write data to multiple files. Following program illustrates the use of this class :

import java.io.*;
public class CharArrayWriterDemo {
   public static void main(String args[]) {
      try {
         String str = "Learning Java is fun";
         CharArrayWriter cw = new CharArrayWriter();
         cw.write(str);
         FileWriter fw1 = new FileWriter("data1.txt");
         FileWriter fw2 = new FileWriter("data2.txt");
         FileWriter fw3 = new FileWriter("data3.txt");
         cw.writeTo(fw1);
         cw.writeTo(fw2);
         cw.writeTo(fw3);
         fw1.close();
         fw2.close();
         fw3.close();
         System.out.println("data written to three files");
      } catch(Exception e) {
         System.out.println(e);
      }
   }
}
Run this program in your system to perform file operations  


SequenceInputStream class
This class is used to read data from multiple streams. Following program demonstrates the usage of this class where the input stream is connected to two files and the contents of those files are read.

import java.io.*;
public class SequenceInputStreamDemo {
   public static void main(String args[]) {
      try {
         FileInputStream fr1 = new FileInputStream("data1.txt");
         FileInputStream fr2 = new FileInputStream("data2.txt");
         SequenceInputStream seq = new SequenceInputStream(fr1, fr2);
         int x;
         while((x = seq.read()) != -1) {
             System.out.print((char)x);
         }
         fr1.close();
         fr2.close();
      } catch(Exception e) {
         System.out.println(e);
      }
   }
}
Run this program in your system to perform file operations  


Read / Write primitive Data Type
We have seen how to read / write characters or bytes in a file. Now we will illustrate how to read and write primitive data types like int, float, etc. For this we will use DataInputStream and DataOutputStream classes as wrappers over FileInputStream and FileOutputStream classes respectively. Following programs writes some float values in a file and reads them back.

import java.io.*;
public class PrimitiveDemo {
   public static void main(String args[]) {
      try {
         // File writing
         FileOutputStream ofile = new FileOutputStream("float.txt");
         DataOutputStream dos = new DataOutputStream(ofile);
         dos.writeFloat(12.37f);
         dos.writeFloat(3.79f);
         dos.writeFloat(76.29f);
         ofile.close(); //close the stream
         System.out.println("Data written to the file ...");

         // File reading
         System.out.println("Reading contents from the file ...");
         FileInputStream ifile = new FileInputStream("float.txt");
         DataInputStream dis = new DataInputStream(ifile);
         for ( int i = 0; i < 3; i++ ) {
            float f = dis.readFloat();
            System.out.print(f + " ");
         }
         System.out.println();
         ifile.close();
      } catch(Exception e) {
         System.out.println(e);
      }
   }
}
Run this program in your system to perform file operations  


A simple file copy program
Following program creates a copy of a file by reading the source file character by character and writing to the destination file. We can read it byte by byte also incase the file to be copied is not the textual file.

import java.io.*;
public class FileCopyDemo {
   public static void main(String args[]) {
      FileInputStream ifile = null;
      FileOutputStream ofile = null;
      try {
         ifile = new FileInputStream("str.txt");
         ofile = new FileOutputStream("str_copy.txt");
         int x;
         while((x = ifile.read()) != -1) {
            ofile.write((char)x);
         }
         System.out.println("File copy done ... ");
      } catch(Exception e) {
         System.out.println(e);
      } finally {
         try {
            ifile.close();
            ofile.close();
         } catch(Exception e) { }
      }
   }
}
Run this program in your system to perform file operations  

Back | Next