Copying file using FileStreams in Java

1.6

We can copy a file from one location to another using FileInputStream and FileOutputStream classes in Java.
For this we have to import some specific classes of java.io package. So for instance let us include the entire package with statement import java.io.*;

The main logic of copying file is to read the file associated to FileInputStream variable and write the read contents into the file associated with FileOutputStream variable.

Methods used in the program

  1. int read(); Reads a byte of data. Present in FileInputStream. Other versions of this method : int read(byte[] bytearray) and int read(byte[] bytearray, int offset, int length)
  2. void write(int b) : Writes a byte of data. Present in FileOutputStream. Other versions of this method : void write(byte[] bytearray) and void write(byte[] bytearray, int offset, int length);
/* Program to copy a src file to destination.
   The name of src file and dest file must be
   provided using command line arguments where
   args[0] is the name of source file and
   args[1] is name of destination file */

import java.io.*;
class src2dest
{
    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() will readonly 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();
    }
}

This article is contributed by Parul Dang. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



1.6 Average Difficulty : 1.6/5.0
Based on 3 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.