How to move folders with files inside them in Java?

2

I have the following dilemma. By day I have X number of folders in a directory that need to be moved to another directory and then make a backup of those files. I am creating a Java program to automate the process but I have problems when 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 exception and tells me that my routes "ARE A DIRECTORY"; which is exactly what I'm wanting to move.

How can I solve 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 class File:

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();
}
}

}
    
asked by Nacho Zve De La Torre 07.08.2018 в 20:32
source

1 answer

2

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:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 *
 * @author jorgesys
 */
public class CopyDirectories {

    public static void copy(File sourceLocation, File targetLocation) throws IOException {
        if (sourceLocation.isDirectory()) {
            copyDirectory(sourceLocation, targetLocation);
        } else {
            copyFile(sourceLocation, targetLocation);
        }
    }

     public static void copy(String sSourceLocation, String stargetLocation) throws IOException {         
         File sourceLocation = new File(sSourceLocation);
         File targetLocation = new File(stargetLocation);

        if (sourceLocation.isDirectory()) { //Es directorio.
            copyDirectory(sourceLocation, targetLocation);
        } else { //Es archivo.
            copyFile(sourceLocation, targetLocation);
        }
    }

    private static void copyDirectory(File source, File target) throws IOException {
        if (!target.exists()) {
            //No existe directorio destino, lo crea.
            target.mkdir();
        }
        for (String f : source.list()) {
            //Copia archivos de directorio fuente a destino.
            copy(new File(source, f), new File(target, f));
        }
    }

    private static void copyFile(File source, File target) throws IOException {
        try (
            InputStream in = new FileInputStream(source);
            OutputStream out = new FileOutputStream(target)) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
        }
    }

}

This is an example of how to use the class:

   //Directorio fuente.
   String pathSource = "C:\Data\";
   //Directorio destino.
   String pathTarget = "C:\Data\respaldos\respaldo_Data\";
   //Realiza la copia.
   CopyDirectories.copy(pathSource, pathTarget);
    
answered by 07.08.2018 / 20:54
source