Java Move File | Directory Method with Examples Code

A moving a file programmatically seems a tough task but it’s not. You have just need to knowledge about Java File Handling and basic controls statements in java. Some application has a need to move single or multiple files (directory) to another place in the application for better management. This tutorial you will learn about How to Java Move File programmatically with examples.

Java provides a method to Move file. It could be entire file or files inside a directory. Before reading this tutorial we suggest reading a how-to Create, Write and Delete tutorial of the java file.

Java Move File Directory Method with Examples

A Ways to Move File in Java

  • Files.Path move() method
  • Using 2 methods – Java.io.File.renameTo() and Java.io.File.delete() methods:

Let’s start Java move file examples

# Using a Files.Path move() method

A standard move() method using NIO, where you need the pass a source file name and destination of file. You can change the name of file also and other opetion are optional.

Syntax

Need to import a java.nio package.

Simple Example

How to move a file from one folder to another in java example code.

Output: A GIF output for how program has worked.

#Using a renameTo() and delete() java File methods

In this way, you have to copy a file and delete the original file. For that there will 2 methods involved Java.io.File.renameTo() and Java.io.File.delete().

Complete Example

Here we used an if-else condition statement, where the file will delete only if file renamed else messages will print failed.

Output: File moved successfully

How it worked?

Here is diagram for upper example how project structure and file moved one directory to another.

Question: How Java move all files from one directory to another?

Answer: First check its directory or not then count the number of the file in the directory. Run the java for loop and move all files.

Task: How to java move file to another directory overwrite?

Answer: do solve this question and write in a comment. We will update a best answers in this tutorial.

Official doc link – https://docs.oracle.com/javase/tutorial/essential/io/move.html

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 Move File are 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.