Error copying a file in java

2

What I'm trying to do is copy the image inside the directory directory but when I execute the method, nothing happens but the directory becomes an arhivo that I have to do to make it work for me.

public static void copyFile(String origen, String destino) throws IOException {
    Path FROM = Paths.get(origen);//img/imagen1.jpg
    Path TO = Paths.get(destino);//img/directorio
      System.out.println("from: "+ FROM);
      System.err.println("TO: "+ TO);
//        sobreescribir el fichero de destino, si existe, y copiar
//        los atributos, incluyendo los permisos rwx
    CopyOption[] options = new CopyOption[]{
      StandardCopyOption.REPLACE_EXISTING,
      StandardCopyOption.COPY_ATTRIBUTES
    }; 
    Files.copy(FROM, TO, options);
}
    
asked by Eduar O Ortz 15.06.2016 в 14:56
source

1 answer

2

The second parameter should indicate the end / target route where you are going to save the file, not the directory where you want to save it. Files#copy what you will do is copy or replace a file, so you are asked for the full path where you want to copy (including the final file name). By default, if you do not specify StandarCopyOption.REPLACE_EXISTING and if the file exists, the copy will fail.

Paths origen = Paths.get("/home/usuario/archivo.pdf");
Paths objetivo = Paths.get("/home/usuario/Documentos/archivo-final.pdf");
CopyOption[] options = new CopyOption[]{
    StandardCopyOption.REPLACE_EXISTING,
    StandardCopyOption.COPY_ATTRIBUTES
}; 
Files.copy(origen, objetivo, options);
    
answered by 15.06.2016 в 15:08