30/08/2014

[Java] move file or directory

Java versions before 7 amazingly lack a simple (one method) way of moving a file or directory to another directory.

Luckily there's the Apache Commons IO library. Using that, you would do something like:

import java.util.*;
import java.io.*;
import org.apache.commons.io.FileUtils;

public void move(String fromDir, String toDir){
//moveToDirectory(File, File, createDestDir), we MUST create two File objects before!
File from = new File(fromDir);
File to = new File(toDir);
/*returns void, throws exceptions: 
NullPointerException - if source or destination is null
FileExistsException - if the directory or file exists in the destination directory
IOException - if source or destination is invalid or if an IO error occurs moving the file*/
FileUtils.moveToDirectory(from, to, false);
}

No comments:

Post a Comment

With great power comes great responsibility