Ad Code

Responsive Advertisement

Ticker

6/recent/ticker-posts

Java Program to Copy the File into Same or Different Directory

Java Program to Copy the File into the Same/Different Directory


Java Program to Copy the File - 

import java.io.*;

 

// Main Class

public class copy {

 

    // Main driver method

    public static void main(String[] args)

        throws IOException

    {

 

        FileInputStream ab = null;

        FileOutputStream cd = null;

 

        // Try block to check for exceptions

        try {

        // Custom directory path on local machine

            ab = new FileInputStream(

                "D:\\Manthan\\Java\\output.txt");

      // Custom directory path on local machine

            cd = new FileOutputStream(

                "D:\\Manthan\\Java\\codingeazy22.txt");

                 int c;

                while ((c = ab.read()) != -1) {

             // Writing to output file of the specified

                // directory

                cd.write(c);

            }

            System.out.println(

                "Copied the File Successfully");

        }

        finally {

       // Closing the streams

       if (ab != null) {

        // Closing the fileInputStream

                cd.close();

            }

            if (ab != null) {

           // Closing the fileOutputStream

                cd.close();

            }

        }

    }

}

Output - 

Copied the File Successfully



FileInputStream - Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data such as image data, audio, video etc.

FileOutputStream - Java FileOutputStream is an output stream used for writing data to a file. If you have to write primitive values into a file, use FileOutputStream class.


How the program works?

To run this program successfully, we have first created a file "output.txt" in the given directory then using the program we have copied the file by renaming the file to "codingeazy22.txt".

Post a Comment

0 Comments

Ad Code

Responsive Advertisement