StudyGPT Just Leveled Up – Say Hello to Knowee! 🚀
Knowee
Questions
Features
Study Tools

Develop a Java program to copy the contents of one file to another fileusing FileInputStream and FileOutputStream classes.

Question

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a simple Java program that uses FileInputStream and FileOutputStream to copy the contents of one file to another:

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

public class FileCopy {
    public static void main(String[] args) {
        FileInputStream instream = null;
        FileOutputStream outstream = null;

        try {
            File infile = new File("C:\\Users\\User\\Desktop\\input.txt");
            File outfile = new File("C:\\Users\\User\\Desktop\\output.txt");

            instream = new FileInputStream(infile);
            outstream = new FileOutputStream(outfile);

            byte[] buffer = new byte[1024];

            int length;
            /*copying the contents from input stream to
             * output stream using read and write methods
             */
            while ((length = instream.read(buffer)) > 0) {
                outstream.write(buffer, 0, length);
            }

            //Closing the input/output file streams
            instream.close();
            outstream.close();

            System.out.println("File copied successfully!!");

        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

This program reads the contents of the file at the path "C:\Users\User\Desktop\input.txt" and writes it to a new file at the path "C:\Users\User\Desktop\output.txt". If the operation is successful, it prints "File copied successfully!!". If an IOException occurs, it prints the stack trace of the exception.

Please replace "C:\Users\User\Desktop\input.txt" and "C:\Users\User\Desktop\output.txt" with the paths of your source and destination files respectively.

This problem has been solved

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.