I have the following dilemma. Per day I have X number of folders in a directory that need to be moved to another directory to then back up those files. I'm creating a Java program to automate the process but I'm having trouble moving the folders (and the files inside them, in this case .tif images) to the new directory.
I have the following code that does not work for me since it generates a FileNotFoundException and tells me that my paths "ARE A DIRECTORY"; which is exactly what I'm wanting to move.
How can i fix this ??
package ilm.copy;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author I de la Torre
*/
public class ILMCopy {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
/*
Archivo a;
//Path originalPath = FileSystems.getDefault().getPath("E:\\CV_REPOSIT");
Path originalPath = FileSystems.getDefault().getPath("/home/incentivate/Desktop/origen");
Path destinationPath = FileSystems.getDefault().getPath("/home/incentivate/Desktop/destino");
//System.out.println(originalPath.getFileName());
a = new Archivo();
a.moverArchivo(originalPath, destinationPath);
*/
final String dirOrigen = "/home/incentivate/Desktop/origen/prueba";
final String dirDestino = "/home/incentivate/Desktop/destino/prueba";
File f = new File(dirOrigen);
File f2 = new File(dirDestino);
try {
Archivo.copyFiles(f, f2);
} catch (IOException ex) {
Logger.getLogger(ILMCopy.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
This is my File class:
package ilm.copy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Archivo {
final static Logger LOGGER = Logger.getAnonymousLogger();
/*
public void moverArchivo(Path origin, Path destiny) {
try {
Files.move(origin, destiny, StandardCopyOption.REPLACE_EXISTING);
} catch (FileNotFoundException ex) {
LOGGER.log(Level.SEVERE, ex.getMessage());
} catch (IOException ex) {
LOGGER.log(Level.SEVERE, ex.getMessage());
}
}
*/
public static void copyFiles(File source, File dest)
throws IOException {
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
inputChannel = new FileInputStream(source).getChannel();
outputChannel = new FileOutputStream(dest).getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
}catch(Exception ex){
ex.printStackTrace();
}
finally {
inputChannel.close();
outputChannel.close();
}
}
}
As an option you can use this class, what it does is basically determine if it is a directory or a file and copy it, if it is a directory it determines the files it contains and copies them:
This is an example of how to use the class: