How to Move a File in Java - RameshMF/java-io-guide GitHub Wiki
Overview
Java.io.File does not contains any ready make move file method, but you can us renameTo() method to move a file.
Move File Example
- Create a file named "sample.txt" in directory "C:/workspace".
- Create File class object by passing file absolute location path "C:/workspace/sample.txt".
- We need to passs 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!");
}
}
}