Failed to copy an entire directory and its files

0

I need to copy an entire directory containing files inside using Java NIO2 with FileChannels . But I can only copy the files into the directory.

Here is the code I'm using to copy the files:

public static void copiaDestino(File destino, File origem) throws IOException{

    FileChannel inChannel = new FileInputStream(origem).getChannel();
    FileChannel outChannel = new FileOutputStream(destino).getChannel();
    try{
        int maxCont = (64 * 1024 * 1024) - (32 * 1024);
        long size = inChannel.size();
        long position = 0;

        while (position < size){
            position += inChannel.transferTo(position, size, outChannel);
        }
        }finally{
            if(inChannel != null){
                inChannel.close();
            }
            if(outChannel != null){
                outChannel.close();
            }
        }
    }
}
    
asked by anonymous 27.08.2015 / 00:33

1 answer

1

This method only copies files and not directories.

By the comments seems to be working when used correctly. I've noticed that it has a parameter inversion that makes its use not so intuitive and is probably generating errors because it is doing the opposite of what you think.

For lack of information I can not help more than this.

//note a inversão dos parâmetros aqui
public static void copiaDestino(File origem, File destino) throws IOException{

    FileChannel inChannel = new FileInputStream(origem).getChannel();
    FileChannel outChannel = new FileOutputStream(destino).getChannel();
    try{
    int maxCont = (64 * 1024 * 1024) - (32 * 1024);
    long size = inChannel.size();
    long position = 0;

    while (position < size){
        position += inChannel.transferTo(position, size, outChannel);
    }
    }finally{
    if(inChannel != null){
        inChannel.close();
    }
    if(outChannel != null){
        outChannel.close();
    }
}

No main() :

try {
    File origem = new File("C:\Novapasta\server.sql");
    File destino = new File("C:\t");
    copiaDestino(origem, destino)
} catch (Exception ex) { //isto só é útil aqui porque é o main
    System.out.println("Deu erro");
}

I placed GitHub for future reference .

    
27.08.2015 / 14:08