2

Tengo el siguiente dilema. Por día tengo X cantidad de carpetas en un directorio que necesitan ser movidas a otro directorio para luego hacer un backup de esos archivos. Estoy creando un programa Java para automatizar el proceso pero tengo problemas a la hora de mover las carpetas (y los archivos dentro de ellas, en este caso imagenes .tif) al nuevo directorio.

Tengo el siguiente código que no me funciona ya que me genera una excepción FileNotFoundException y me dice que mis rutas "SON UN DIRECTORIO"; que es exactamente lo que estoy queriendo mover.

Como puedo solucionar esto ??

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

}

Esta es mi clase Archivo:

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

}
3
  • 1
    Es correcto lo que tratas Nacho, pero recuerda que un directorio puede tener dentro subdirectorios.
    – Jorgesys
    el 7 ago. 2018 a las 19:16
  • 1
    Muchisimas gracias por tu genial clase hermano !! La miré y la voy a utilizar para mi trabajo! Te mando un fuerte abrazo el 7 ago. 2018 a las 19:22
  • 1
    un placer ayudarte, saludos!
    – Jorgesys
    el 7 ago. 2018 a las 19:26

1 respuesta 1

2

Como opción puedes usar esta clase, lo que realiza es básicamente determinar si es un directorio o un archivo y copiarlo, si es un directorio determina los archivos que contiene y los copia:

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

}

Este es un ejemplo de como usar la clase:

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

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.