Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- public class BackupJob implements Runnable {
- private File startDir;
- private File destDir;
- private Filter filter;
- public BackupJob(File s, File d){
- this(s, d, null);
- }
- public BackupJob(File s, File d, Filter f){
- startDir = s;
- destDir = d;
- filter = f;
- }
- @Override
- public void run() {
- try {
- validateDirectory(startDir);
- validateDirectory(destDir);
- File[] contents = startDir.listFiles();
- for (int i = 0; i < contents.length; i++){
- recurse(contents[i]);
- }
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- private void recurse(File file){
- if (!filter.isAcceptable(file))
- return;
- File dest = new File (destDir, getRelPath(file, startDir));
- if (file.isDirectory()){
- if(!dest.exists()){
- dest.mkdirs();
- File [] contents = file.listFiles();
- for (int i = 0; i < contents.length; i++){
- recurse(contents[i]);
- }
- }
- } else {
- if(dest.exists() && dest.lastModified() >= file.lastModified()
- && dest.length() == file.length()){
- System.out.println("File exists, not copied.");
- } else {
- dest.getParentFile().mkdirs();
- CopyJob cj = new CopyJob(file, dest);
- //TODO: get job to pool
- }
- }
- }
- //returns the path of f relative to the given root directory
- private String getRelPath (File f, File root){
- String p = f.getAbsolutePath();
- return p.replace(f.getParent(), "");
- }
- /**
- * Directory is valid if it exists, does not represent a file, and can be read.
- */
- private void validateDirectory (File aDirectory) throws FileNotFoundException {
- if (aDirectory == null) {
- throw new IllegalArgumentException("Directory should not be null.");
- }
- if (!aDirectory.exists()) {
- throw new FileNotFoundException("Directory does not exist: " + aDirectory);
- }
- if (!aDirectory.isDirectory()) {
- throw new IllegalArgumentException("Is not a directory: " + aDirectory);
- }
- if (!aDirectory.canRead()) {
- throw new IllegalArgumentException("Directory cannot be read: " + aDirectory);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement