Reading and writing a file in Java using FileInputStream and FileOutputStream

In this Java tutorial, we will learn about file handling in Java. Basically, we will learn reading and writing a file in Java using FileInputStream and FileOutputStream. The java.io package contains every class to perform input and output operations in Java.

File Class

Let’s first talk about File. File class in Java is an abstract representation of file and directory pathname. The File class contains several methods for deleting and creating files, creating new directories, listing the contents of a directory etc. A File object represents the actual file or directory on the disk.
We can create a File by passing filename or directory name to the File class constructor.

File inputFile = new File("C:/Users/Vikrant/Desktop/program1");

Reading and Writing a File

A stream is defined as a sequence of data or sequence of objects. We will talk about two important streams in Java which are used in this tutorial. First, FileInputStream in java reads data from the file. Second, FileOutputStream creates a file and writes data into the file. These two streams are byte streams. Byte streams process data byte by byte.
Creating FileInputStream and FileOutputStream from a file :

FileInputStream fin = new FileInputStream(inputFile);
FileOutputStream fout= new FileOutputStream(outputFile);

Program for Reading and Writing a File in Java

The program1.txt file contains the text:

Hello from codespeedy!

 

import java.io.*;

public class fileHandling {
    public static void main(String[] args) {

        File inputFile = new File("C:/Users/Vikrant/Desktop/program1.txt");

        File outputFile= new File("C:/Users/Vikrant/Desktop/program2.txt");

        try {
            FileInputStream fin = new FileInputStream(inputFile);
            FileOutputStream fout= new FileOutputStream(outputFile);

            FileReader fr= new FileReader(outputFile);

            //Writing the contents of program1 to program2
            int ch;
            while ((ch= fin.read())!= -1){
                fout.write(ch);
            }

            int f;
            while ((f=fr.read())!=-1){
                System.out.print((char)f);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

Hello from codespeedy!

This program writes the contents of program1.txt into program2.txt. The output shows the contents of program2.txt after writing. We can also use FileReader to read files in Java. The read() method of FileInputStream reads the contents of program1 byte by byte. And, the write() method of FileOutputStream writes into the output file program2.



 

Also, read:

 

Leave a Reply

Your email address will not be published. Required fields are marked *