2011-03-20 39 views

Respuesta

17

Apache Commons IO puede hacer el truco para usted. Eche un vistazo al FileUtils.

+0

enlace está abajo. pls update – 4ndro1d

+1

http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#copyFile%28java.io.File,%20java.io.File%29 – Raghunandan

44

más que elegir:

  • FileUtils de Apache Commons IO (la manera más fácil y segura)

Ejemplo con FileUtils:

File srcDir = new File("C:/Demo/source"); 
File destDir = new File("C:/Demo/target"); 
FileUtils.copyDirectory(srcDir, destDir); 
  • manualmente, example before Java 7 (CAMBIO: cerrar las transmisiones en el bloque final ck)
  • manualmente, Java> = 7

Ejemplo con función AutoCloseable en Java 7:

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

private void copyDirectory(File source, File target) throws IOException { 
    if (!target.exists()) { 
     target.mkdir(); 
    } 

    for (String f : source.list()) { 
     copy(new File(source, f), new File(target, f)); 
    } 
} 

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

Esto funciona, pero si ocurre una excepción, no cerrarás las transmisiones: debes agregar un bloque try catch finally. –

+0

@Tim, eso es cierto. Fijo – smas

2

vistazo a java.io.File para un grupo de funciones.

iterará a través de la estructura existente y mkdir, guarde etc. para lograr una copia en profundidad.

Cuestiones relacionadas