How do I copy file?

This example demonstrates how to copy file using the Java IO library. Here we will use the and it’s tandem the class.



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 = != -1) {
                fos.write(buffer, 0, read);
        } catch (IOException e) {

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.