In this post, we will learn how to move a file in Java using Java7 NIO or Apache Commons IO. As part of the core java tutorials, we will cover following options.
NIO Package in JDK7 added several enhancements to file API in Java including Path and convenient Files class.
public class MoveFile {
public static void main(String[] args) throws IOException {
Path source = Paths.get("/Users/umesh/personal/tutorials/source/store.html");
Path target = Paths.get("/Users/umesh/personal/tutorials/target");
Files.move(source,target.resolve(source.getFileName()));
}
Above code assume that both source and target directory already exists.In case target directory does nor exists, the method will throw code java.nio.file.NoSuchFileException.
You can also use above method to move the directory to the target location by changing the code a little.
public class MoveDirectory {
public static void main(String[] args) throws IOException {
Path source = Paths.get("/Users/umesh/personal/tutorials/source");
Path target = Paths.get("/Users/umesh/personal/tutorials/target");
Files.move(source,target.resolve(source.getFileName()));
}
}
Apache Commons provide easy options to move files/ directories. If you are already using Commons API in your project, there is nothing better than writing few lines to get your work done.
public class MoveDirectoryApache {
public static void main(String[] args) throws IOException {
File source = FileUtils.getFile("/Users/umesh/personal/tutorials/source/bower.json");
File target = FileUtils.getFile("/Users/umesh/personal/tutorials/target/bower.json");
FileUtils.moveFile(source, target);
}
}
If you want API to create a directory automatically, use moveFileToDirectory(File srcFile, File destDir, boolean createDestDir)
and set createDestDir
as true
public class MoveDirectoryApache {
public static void main(String[] args) throws IOException {
File source = FileUtils.getFile("/Users/umesh/personal/tutorials/source");
File target = FileUtils.getFile("/Users/umesh/personal/tutorials/target");
FileUtils.moveDirectory(source, target);
}
}
In this post, we learn how to move a file in Java. With Java7 NIO moving a file or directory is really easy and Apache Commons always have handy methods for these tasks.
All the code of this article is available Over on Github. This is a Maven-based project.
References
Hello!! Welcome to the Java Development Journal. We love to share our knowledge with our readers and love to build a thriving community.
Leave a Reply