Open In App

Copying file using FileStreams in Java

Improve
Improve
Like Article
Like
Save
Share
Report

The main logic of copying a file is to read the file associated with FileInputStream variable and write the read contents into the file associated with FileOutputStream variable. We can copy a file from one location to another using FileInputStream and FileOutputStream classes in Java. Now before adhering forward let us discuss essential methods that will be used in the program. 

Method 1: read(): Reads a byte of data. Present in FileInputStream. 

Return type: An integer value 

Syntax: Other versions 

int read(byte[] bytearray

or

int read(byte[] bytearray, int offset, int length)

Method 2: write(int b): Writes a byte of data. Present in FileOutputStream

Syntax:

void write(byte[] bytearray)

or

void write(byte[] bytearray, int offset, int length)

Implementation: We will be creating two files named “demo.rtf” and “outputdemo.rtf” as another file where no content is there. Below is an image of the “demo.rtf” file as a sample input image.

  • First, we will create two objects of the File class, one referring to FileInputClass and the other for FileOutputStream Class.
  • Now we will create objects of FileInputStream class and FileOutputStream class prior to creating variables and assigning null to corresponding datatypes.
  • Pass respective objects of FileInputStream and FileOutputStream objects
  • Now using loops keep reading from a file and write it to another file using FileOuputStream using the read() and write() methods.

Tip: It is good practice to close the streams to avoid memory leakage.      

Example 1:

Java




// Java Program to Illustrate File InputStream and File
 
// Importing required classes
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating object of File class
        // Passing files from directory of local machine
        File file = new File(
            "/Users/mayanksolanki/Desktop/demo.rtf");
        File oFile = new File(
            "/Users/mayanksolanki/Desktop/outputdemo.rtf");
 
        // Now creating object of FileInputStream
        // Here they are variables
        FileInputStream fis = null;
        FileOutputStream fos = null;
 
        try {
            // Now we make them as objects of both classes
            // and passed reference of file in directory
            fis = new FileInputStream(file);
            fos = new FileOutputStream(oFile);
        }
 
        // Catch block to handle exceptions
        catch (FileNotFoundException e) {
 
            // Display message if exception occurs
            // File Not Found or Path is Incorrect
            System.out.println(e.printStackTrace());
        }
 
        try {
 
            // Now let us check how many bytes are available
            // inside content of file
            fis.available();
        }
 
        catch (Exception e) {
            e.printStackTrace();
        }
 
        // Using while loop to
        // write over outputdemo file
        int i = 0;
        while (i = fis.read() != -1) {
            fos.write(i);
        }
 
        // It will execute no matter what
        // to close connections which is
        // always good practice
        finally
        {
 
            // Closing the file connections
 
            // For input stream
            if (fis != null😉 {
                fis.clsoe();
            }
 
            // For output stream
            if (fos != null) {
                fos.close();
            }
        }
    }
}


Output: The same content will be reflected back in the “outputdemo.rtf” file as seen below in the “demo.rtf” file. 

Example 2:

Java




// Java Program Illustrating Copying a src File
// to Destination
 
// Importing required classes
import java.io.*;
 
// Main class
// src2dest
class GFG {
 
    // Main driver method
    public static void main(String args[])
        throws FileNotFoundException, IOException
    {
 
        // If file doesnot exist FileInputStream throws
        // FileNotFoundException and read() write() throws
        // IOException if I/O error occurs
        FileInputStream fis = new FileInputStream(args[0]);
 
        // Assuming that the file exists and
        // need not to be checked
        FileOutputStream fos
            = new FileOutputStream(args[1]);
 
        int b;
        while ((b = fis.read()) != -1)
            fos.write(b);
 
        // read() method will read only next int so we used
        // while loop here in order to read upto end of file
        // and keep writing the read int into dest file
        fis.close();
        fos.close();
    }
}


Output:

Output Explanation: The name of the src file and dest file must be provided using command line arguments where args[0] is the name of the source file and args[1] is the name of the destination file. 



Last Updated : 18 Apr, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads