Reading from and Writing to Files

In this tutorial, we will discuss how to copy the contents of one file into another using Byte streams and Character streams. Basically, we will learn here how to develop Java programs to read from and write to files using I/O streams.

 

1. Reading and Writing Bytes

Java supports the following I/O byte streams.

  • FileInputstream
  • FileOutputStream 

The FileInputStream and FileInputStream classes are designed for reading and writing image files as it reads and writes a stream of raw bytes.

FileInputstream: This class is a subclass of Inputstream class that reads bytes from a specified file name. The read() method of this class reads a byte or array of bytes from the file. It returns –1 when the end-of-file has been reached. We typically use this class in conjunction with a BufferedInputStream and DataInputstream class to read binary data. To read text data, this class is used with an InputStreamReader and BufferedReader class.

FileOutputStream: This class is a subclass of OutputStream that writes data to a specified file name. The write() method of this class writes a byte or array of bytes to the file. We typically use this class in conjunction with a BufferedOutputStream and a DataOutputStream class to write binary data. To write text, we typically use it with a PrintWriter, BufferedWriter and an OutputStreamWriter class. This class throws FileNotFoundException, if the specified file does not exist.

 

As an example, Program FileTest03.java shows how to use the FileInputStream and FileOutputStream classes to read and write files. It copies a file mytext.txt (which must exist in the directory where we execute this program) to another file named mytextcopy.txt, which is created if it does not exist.

FileTest03.java

// Copying contents of one file into another using byte stream
import java.io.*;

public class FileTest03 {
    
    public static void main(String[] args) {
        File f1;
        File f2; 
        FileInputStream in = null;
        FileOutputStream out = null;
        int c;
        
        try {
            f1 = new File("mytext.txt");
            f2 = new File("mytextcopy.txt");
            in = new FileInputStream(f1);
            out = new FileOutputStream(f2);
            
            while((c = in.read()) != -1) {
                out.write(c);
            }    
        }
        catch(IOException e) {
            System.out.println(e);
        }
        finally {
            try {
                in.close();
                out.close();
            }
            catch(Exception e) {  
                System.out.println(e);
            }
        }
        
    }

}

 

Let’s consider file mytext.txt has the following contents:

Hi This is from Tech Guru.
I am now writing Java I/O.
Happy Learning Friends.
It’s Good Bye from me.

 

If we run the program named FileTest03.java then the contents of the above text file mytext.txt will be copied to mytextcopy.txt file. This example demonstrates that although FileInputStream and FileOutputStream are more suitable to read and write image files, it is legal to use them for text files too.

 

2. Reading and Writing Characters

However, the FileReader and FileWriter classes are more suitable to read and write streams of characters (from text files). See the program (FileTest04.java) below:

FileTest04.java

// Copying content of one file into another using character stream
import java.io.*;

public class FileTest04 {

public static void main(String[] args) {
File f1;
File f2;
FileReader in = null;
FileWriter out = null;
int c;

try {
f1 = new File("mytext.txt");
f2 = new File("mytextcopy.txt");
in = new FileReader(f1);
out = new FileWriter(f2);

while((c = in.read()) != -1) {
out.write(c);
}
}
catch(IOException e) {
System.out.println(e);
}
finally {
try {
in.close();
out.close();
}
catch(Exception e) {
System.out.println(e);
}
}

}
}

 

The above program will generate the same output as program FileTest04.java does: The contents of the text file mytext.txt will be copied to mytextcopy.txt file.

 

The above program can also be re-written using low-level and high-level stream combo. We can modify it using BufferedReader-FileReader and BufferedWriter-FileWriter combination. This Java program will read and write files line by line. See a simplified version of the modified program below.

File04a.java

// File copying using high and low level streams
import java.io.*;

public class FileTest04a {

public static void main(String[] args) throws IOException {

File inputFile = new File("mytext.txt");
File outputFile = new File("mytextcopy.txt");
BufferedReader in = new BufferedReader(new FileReader(inputFile));
BufferedWriter out = new BufferedWriter(new FileWriter(outputFile));
String line;
while ((line = in.readLine()) != null) {
out.write(line);
out.newLine();
}
in.close();
out.close();
}

}