How to copy Files from one directory to other in Java

I have been programming in Java for a long time and you won't believe but there was no file copy method in the Java API until Java 7. At that time, our options were either write it ourself, using a FileInputStream, a FileOutputStream and a buffer to copy bytes from one to the other - or better yet, use the FileChannel.transferTo() method or just use the Apache Commons' FileUtils which was a life save those days and even today. JDK has evolved now and you have a decent API to copy files from one directory to another. In this article, I'll show you both the pre-Java code for copying files from one directory to other as well post Java 7 code which makes this task a lot easier.


1. Copying File from Directory to other before Java 7

Dependency: Apache Commons IO

1) FileUtils.copyFile(File source, File destination)

This method copies a file to a new location preserving file timestamp
This method copies the contents of the specified source file to the specified destination file. The directory holding the destination file is created if it does not exist. If the destination file exists, then this method will overwrite it.


import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

/**
* Java program to copy a file from one directory to another e.g. from src to dest
*
* @author Javin
*/
public class FileCopyDemo {

    public static void main(String args[]) {

        // Using Apache Commons FileUtils class
        File srcFile = new File("bin/HelloWorld.class");
        File destFile = new File("target/HelloWorld.class");
        try {
            FileUtils.copyFile(srcFile, destFile);
            System.out.println("File successfully copied in Java");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
Output:
System.out.println("File successfully copied in Java");


How to copy Files from one directory to other in Java



1. 2 Copies a file to a directory preserving the timestamp

This method copies the contents of the specified source file to a file of the same name in the specified destination directory. The destination directory is created if it does not exist. If the destination file exists, then this method will overwrite it.


import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

/**
* Java program to copy a file from one directory to another like from src to dest
*
* @author Javin Paul
*/
public class Testing {

    public static void main(String args[]) {

        // Using Apache Commons FileUtils class
        File srcFile = new File("bin/HelloWorld.class");
        File destDir = new File("target");
        try {
            FileUtils.copyFileToDirectory(srcFile, destDir);

            System.out.println("File successfully copied to destination directory in Java");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

Output
File successfully copied to destination directory in Java



2. Copying Files from one Directory to Other using Java 7 NIO 2 API

In Java 7, there is a standard method to copy files in java:


Files.copy.

It integrates with O/S native I/O for high performance.


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import static java.nio.file.StandardCopyOption.*;
import static java.nio.file.LinkOption.*;

/**
* Java program to copy file using Java 7 Files.copy() method
*
* @author Javin Paul
*/
public class FileCopyDemo {

    public static void main(String args[]) {

        try {
            Path bytes = Files.copy(
                    new Java.io.File("bin/HelloWorld.class").toPath(),
                    new java.io.File("target/HelloWorld.class").toPath(),
                    REPLACE_EXISTING,
                    COPY_ATTRIBUTES,
                    NOFOLLOW_LINKS);
            System.out.println("File successfully copied using Java 7 way");

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

You can also copy files in Java by writing code using FileInputStream and FileOuputStream, but that's just not required, given you have Java 7 installed.

Alternatively Apache commons IO FileUtils class is also handy. For high-speed file copy and transfer, you can also take advantage of java.nio and FileChannel class but beware that there is a bug in Windows, which prevents you to transfer more than 64GB of channel data. Windows bug around the transferFrom not able to copy streams larger than 64MB in one piece?


Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!


Other Programming Articles you May like
  • The 2020 Java Developer RoadMap (guide)
  • 10 Things Every Java Developer Should Learn (tips)
  • 10 Tools Every Java Developer Should Learn (tools)
  • 10 Articles Every Programmer Must read (see here)
  • 5 Programming language every Programmer should learn (see here)
  • 10 Interview Questions Every Programmer should know (see here)
  • 6 Books to Learn and Master Programming and Coding (see here)
  • 10 Object-Oriented Design Principles Java Programmer should know (read here)
  • 10 Java and Web Development Frameworks for Programmers (frameworks)
  • How to become a DevOps Engineer in 2020? (roadmap)
  • How to become a React JS Developer in 2020? (roadmap)
  • 20 libraries Every Java Developer should know (libraries)
Thanks for reading this article so far. If you like this article, then please share it with your friends and colleagues. If you have any questions or feedback, then please drop a note.

P. S. - If you are new to Java world and looking for free courses to learn Java from scratch then you can also take a look at my favorite free Java courses on Medium. It has some of the best free Java training courses to learn Java online.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.