2011-03-22 14 views
8

Tengo un archivo example.tar.gz y necesito copiarlo a otra ubicación con un nombre diferente example_test.tar.gz. Probé conCopie y cambie el nombre del archivo en una ubicación diferente

private void copyFile(File srcFile, File destFile) throws IOException 
    { 
      InputStream oInStream = new FileInputStream(srcFile); 
      OutputStream oOutStream = new FileOutputStream(destFile); 

      // Transfer bytes from in to out 
      byte[] oBytes = new byte[1024]; 
      int nLength; 
      BufferedInputStream oBuffInputStream = 
          new BufferedInputStream(oInStream); 
      while ((nLength = oBuffInputStream.read(oBytes)) > 0) 
      { 
       oOutStream.write(oBytes, 0, nLength); 
      } 
      oInStream.close(); 
      oOutStream.close(); 
    } 
} 

donde

String from_path=new File("example.tar.gz"); 
File source=new File(from_path); 

File destination=new File("/temp/example_test.tar.gz"); 
      if(!destination.exists()) 
       destination.createNewFile(); 

y luego

copyFile(source, destination); 

pero no funciona. La ruta está bien. Imprime que los archivos existen. ¿Alguien puede ayudar?

+0

tratan 'flush()' 'sus fuentes antes de cerrar()' ing ella. –

+0

Corrija este código en su publicación: 'String from_path = new File (" example.tar.gz ");' –

+2

@Mohamed, flush no es necesario antes de cerrar – bestsss

Respuesta

6
I would suggest Apache commons FileUtils or NIO (direct OS calls) 

o simplemente esta

Créditos a Josh - standard-concise-way-to-copy-a-file-in-java


File source=new File("example.tar.gz"); 
File destination=new File("/temp/example_test.tar.gz"); 

copyFile(source,destination); 

actualizaciones:

cambiado a partir de TransferTo @bestss

public static void copyFile(File sourceFile, File destFile) throws IOException { 
    if(!destFile.exists()) { 
     destFile.createNewFile(); 
    } 

    FileChannel source = null; 
    FileChannel destination = null; 
    try { 
     source = new RandomAccessFile(sourceFile,"rw").getChannel(); 
     destination = new RandomAccessFile(destFile,"rw").getChannel(); 

     long position = 0; 
     long count = source.size(); 

     source.transferTo(position, count, destination); 
    } 
    finally { 
     if(source != null) { 
     source.close(); 
     } 
     if(destination != null) { 
     destination.close(); 
     } 
    } 
} 
+0

Usar FileStreams puede ser ineficiente para copiar archivos, mira' java.nio.channels.FileChannel.transferTo' – bestsss

Cuestiones relacionadas