Develop a Java program to copy the contents of one file to another fileusing FileInputStream and FileOutputStream classes.
Question
Develop a Java program to copy the contents of one file to another file using FileInputStream
and FileOutputStream
classes.
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.
Similar Questions
Which class in Java is used to read data line by line from a file?OptionsFileInputStreamBufferedReaderFileWriterOutputStream
Which stream class is used to write formatted text to a file in Java?Question 13Answera.PrintWriterb.FileWriterc.FileOutputStreamd.BufferedWriter
An object in the java.io package that lets you print output to a destination such as a file.System.out.printPrintStreamOutputStreamSystem.out.stream
In Java, what does the FileWriter class do?Question 3Answera.Reads data from a fileb.Writes data to a filec.Deletes a filed.Checks if a file exists
Which of these class is not related to input and output stream in terms of functioning?OptionsWriterFileInputStreamReader
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.