File Input Output Operations in Java Using Byte Streams

Java programs can perform I/O operations using byte streams i.e. one byte at a time. All byte stream classes are descended from InputStream and OutputStream. There are several byte stream classes, here we will focus on the file I/O byte streams, FileInputStream and FileOutputStream. The following Java code copies one byte at a time from the input file and writes it to the output file (one byte at a time). It also handles IO exception during opening the file, processing the file, and closing the file.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyBytes{
    public static void main(String[] args){
        FileInputStream in = null;
        FileOutputStream out = null;
        
        try{
            in = new FileInputStream("testfiles/inputfile.txt");
            out = new FileOutputStream("testfiles/outputfile.txt");
            
            int c;
            while((c=in.read()) != -1){
                out.write(c);
            }
        }catch(IOException e){
            System.err.println("IOException in processing files: " + e.getMessage());
        }finally{
            try{
                if(in != null){
                    in.close();
                    System.out.println("All data read from input file");
                }
                if(out != null){
                    out.close();
                    System.out.println("All data written to output file");
                }
            }catch(IOException e){
                System.err.println("IOException on closing files: " + e.getMessage());
            }
        }
    }
}

run:
All data read from input file
All data written to output file
BUILD SUCCESSFUL (total time: 0 seconds)

The content of the output file after the program is executed is as follows…

As byte stream is actually a kind of low-level I/O, it should be avoided while reading a very large file.

One comment

  1. whoah this blog is fantastic i really like reading your articles.
    Stayy up the great work! You understand, a lot oof individduals are hunting round for this information, you can help
    them greatly.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.