In this quick tutorial, we will learn different ways to move a file in Java.
1. Move File using File.renameTo() Method
- Create a file named "sample.txt" in the directory "C:/workspace".
- Create File class object by passing file absolute location path "C:/workspace/sample.txt".
- We need to pass the new abstract pathname to renameTo() method to move the file.
- renameTo() method returns true if and only if the renaming succeeded; false otherwise.
- Observe the directory whether the file is moved or not.
import java.io.File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This Java program demonstrates how to move file in Java.
* @author javaguides.net
*/
public class MoveFileExample {
private static final Logger LOGGER = LoggerFactory.getLogger(MoveFileExample.class);
public static void main(String[] args) {
moveFile();
}
public static void moveFile() {
File file = new File("C:/workspace/sample.txt");
boolean move = file.renameTo(new File("C:/workspace/moved/sample.txt"));
if (move) {
LOGGER.info("File is moved successful!");
} else {
LOGGER.info("File is failed to move!");
}
}
}
2. Move File using Files.move() Method
java.nio.file.Files provide several static methods that operate on files, directories, or other types of files. To move a file to a target file, we can use its move() method:import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class Main
{
public static void main(String[] args)
{
File from = new File("src.txt");
File to = new File("dest.txt");
try {
Files.move(from.toPath(), to.toPath(), StandardCopyOption.REPLACE_EXISTING);
System.out.println("File moved successfully.");
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
Reference
- https://docs.oracle.com/javase/10/docs/api/java/io/File.html
- https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/nio/file/Files.html
File Handling Examples
- How to Create a New File in Java
- How to Write to File in Java
- How to delete a file in Java
- How to Copy the File in Java
- How to Move a File in Java
- How to Rename the File in Java
- How to Append to File in Java
- Read the File using BufferReader
- Read File using BufferInputStream
- Read the File using DataInputStream
- Reading a File in Java using BufferedInputStream
- Read a File in Java using BufferedReader
- Java Get File Extension From Filename
- Get File Size in Bytes KB MB GB TB
- How to Check if a File is Empty in Java
Comments
Post a Comment
Leave Comment