Skip to content

Instantly share code, notes, and snippets.

@alashow
Created April 24, 2016 23:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alashow/22b6367f767748180a5c79d476c51ee7 to your computer and use it in GitHub Desktop.
Save alashow/22b6367f767748180a5c79d476c51ee7 to your computer and use it in GitHub Desktop.
package mover;
import java.io.File;
import java.nio.file.Files;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Moves files to folders with name founded year (4 length number in parenthesis) in file name. Can be used for ordering movie files
* Ex.: file name: The Bourne Identity (2002).mp4
* destination folder will be: 2002
*/
public class Mover {
private static Pattern YEAR_PATTERN = Pattern.compile("\\([0-9]{4}\\)");
/**
* @param args first argument will be used as root path
*/
public static void main( String[] args ) {
if (args == null || args.length == 0) {
log("'args' is null or empty");
return;
}
File root = new File(args[0]);
if (! root.exists()) {
log("Root path does not exists");
return;
}
for(String file : root.list()) {
Matcher matcher = YEAR_PATTERN.matcher(file);
if (matcher.find()) {
File yearFolder = new File(root.getAbsolutePath() + "/" + matcher.group(0).replace("(", "").replace(")", ""));
if (! yearFolder.exists()) {
if (! yearFolder.mkdirs()) {
log("Couldn't create folders for path '%s'", yearFolder.getAbsolutePath());
}
}
File movieFile = new File(root.getAbsolutePath() + "/" + file);
if (movieFile.isFile()) {
try {
Files.move(movieFile.toPath(), new File(yearFolder.getAbsolutePath() + "/" + file).toPath());
log("Moving %s to %s", movieFile.toPath().toString(), new File(yearFolder.getAbsolutePath() + "/" + file).toPath().toAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
/**
* Log helper
* @param string string to log
* @param args args to format with
*/
private static void log( String string, Object... args ) {
System.out.println(String.format(string, args));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment