This example demonstrates how to copy file using the Java IO library. Here we will use the java.io.FileInputStream
and it’s tandem the java.io.FileOutputStream
class.
package org.kodejava.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopyDemo {
public static void main(String[] args) {
// Create an instance of source and destination files
File source = new File("source.pdf");
File destination = new File("target.pdf");
try (FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(destination)) {
// Define the size of our buffer for buffering file data
byte[] buffer = new byte[4096];
int read;
while ((read = fis.read(buffer)) != -1) {
fos.write(buffer, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024