Java Copy File | Directory | New Name (Rename) with examples

Copying the file help to change the data without modifying original data. Same as some time required a copy a file and modifying an application. For an example, photo editing application or software has a copy of the original image as a temp file. In this tutorial, you will learn about to write a Java Copy File Program and many related examples on it.

Java Copy File Directory New Name example

Copying a file in java comes under the File Handling. Its important to you learn how to Create, Write, Delete and Move File programmatically in java.

Ways to Copy a File in Java

There are many ways to Copy a file in java, Here is some methods to do it:

  • NIO classes in java – java.nio.channels.FileChannel
  • Apache Commons IO FileUtils
  • Files class – copy() method
  • Operation using InputStream and OutputStream

Let’s start to see examples of Java Copy File

All examples in Java copy file with a new name (Rename). You can use the same name for it in the different file path.

1. Using Channel – NIO classes in java

Output: This output will common for all example of file copying in java

Java Copy File example output
2. Apache Commons IO FileUtils

Apache Commons IO has one method FileUtils.copyFile(File sourceFile, File destinationFile)  easily copy a file. If you are using an Apache Commons IO in the project then you can easily use its methods and classes.

A link of the library –
*Apache Commons IO 2.6 (requires JDK 1.7+)

3. Files class – copy() method

If you are using a using Java SE 7 Files class, then copy() method simply do your work without a lot of code line.

4. Operation using InputStream and OutputStream

This is a basic way to do copy a file. It is slower than other methods because  because Blocking IO and fully stream oriented.

How Java copy directory?

Copying a Java copy folder or directory is the same. See the below example, how to copy directory one place to another place. Note- it will only copy directory on files (inside files in the folder).

Using Files class – copy() method, you can use apache Apache Commons API for copying directory in Java.

Output: You can see the output of example, only folder copy not file.

How Java copy directory example output

Question: How to copy multiple files from one directory to another in java?

Answer: You can do it Using one of the above methods. First, count and get the file path with the name of files using for-loop. Then apply any one of a method inside a loop to do until copy all of files.

You must follow this tutorial and example – Java Move File

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1
Java version 11
All Java Copy File is in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.|

Leave a Reply

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