Problem: Write a Java program to copy the contents of a text file to another text file.
We can easily copy the contents of a file to another by using the File, FileInputStream and FileOutputStream classes in Java. Here is how:
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
// Define the source file and the destination file
File sourceFile = new File("path/to/source/file.txt");
File destinationFile = new File("path/to/destination/file.txt");
// Use a try-with-resources block to automatically close the file streams
try (
// Create input and output streams for the files
InputStream in = new FileInputStream(sourceFile);
OutputStream out = new FileOutputStream(destinationFile)
) {
// Create a buffer to hold data as it is read from the input stream and written to the output stream
byte[] buffer = new byte[1024];
int length;
// Read data from the input stream and write it to the output stream
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
// Print a message to indicate that the file copy was successful
System.out.println("File copy complete.");
} catch (IOException e) {
// Print an error message if there is a problem with the file copy
System.err.println("Error copying file: " + e.getMessage());
}
}
}
Output:
File1.txt:
File2.txt:
In the above program, we copy one file to another using the File Stream classes in Java.
First, we create File
objects for the source and destination files.
Then within the try-with-resources block, we create FileInputStream
and FileOutputStream
objects for the respective files. Doing so ensures that the program will automatically close the file streams when they are no longer needed.
Within the try block, we define a Byte
buffer for holding the input stream data.
We then use a while loop to read data from the input stream and write it to the output stream until there is no more data to read.
In this while loop, the read
method of the FileInputStream
class reads data from the input stream into a buffer and returns the number of bytes read.
The loop continues to execute as long as the read
method returns value greater than 0, which means that there is more data to read. If the read
method returns -1, it means there is no more data to read, therefore the while loop exits.
Notice, the main logic of the program is inside the try block. This is because, if by any cause the copying operation throws an error, the program will not terminate immediately but prints the actuals exception that has occurred.
This is just one way to copy contents of one text file to another in Java. There multiple other ways using which you can copy file using the Java programing language, for example, by sing the Apache commons IO
library or Guava
library.