How to copy a file instead of moving?

0

I have an application made in Java, where I move files from one directory to another and organize them, the problem is that they are moved but not copied, another serious doubt, that if this file is copied, the attributes of the file, for example, the creation date?

What I need to know is how I can copy them instead of moving them, this is the part of the method where I move them using the renameTo .

//Si se realizo con exito el movimiento de archivos
if(bool){ 
    bool = false;
    resultNuFolder = NuCarpetaCnFicha(newPath, noFicha);
    bool = finalArchivo.renameTo(new File(resultNuFolder, oldName));
    if(bool)
        bool=true;
} else {
    System.out.println("El archivo "+ oldName + " no pudo ser cambiado de destino");
}
    
asked by Kevin M. 19.02.2016 в 01:31
source

3 answers

2

From version 7:

bool resultado = Files.copy( origen, destino, StandardCopyOption.COPY_ATTRIBUTES );
if (resultado) { 
    System.out.println("archivo copiado");
}

Regarding the creation dates, here in the documentation, says that the only attribute that works on all platforms is the modification date. Regarding the creation date, it will depend on the platform.

If it was on windows, here you have a class that allows you to change the creation date. But be careful, as mentioned @LuiggiMendoza uses com.sun packages that depend on the implementation of the JVM.

    
answered by 19.02.2016 / 03:18
source
1
  

Files.copy must be the accepted answer, since it has a better performance than other options, but it is only available for Java 7 +

For Java 6, you can use the following method:

public void copy(File original, File destino) throws IOException {
    InputStream in = new FileInputStream(original);
    try {
        OutputStream out = new FileOutputStream(destino);
        try {

            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        } finally {
            out.close();
        }
    } finally {
        in.close();
    }
}

Or use FileUtils from Apache Commons

    
answered by 19.02.2016 в 15:45
0

From Java 7 you can use the class Files of your API called New Input Output Formalemnte NIO .

 Files.copy( from.toPath(), to.toPath() );

You can also specify copy options as a third parameter.

More information: link

    
answered by 19.02.2016 в 03:14