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 create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023