Cómo hacer una copia de un archivo en android?

En mi aplicación quiero guardar una copia de un archivo determinado con un nombre diferente (que obtengo del usuario)

¿Realmente necesito abrir el contenido del archivo y escribirlo en otro archivo?

¿Cuál es la mejor manera de hacerlo?

Para copiar un archivo y guardarlo en su ruta de destino, puede utilizar el método siguiente.

public static void copy(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); try { OutputStream out = new FileOutputStream(dst); try { // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } finally { out.close(); } } finally { in.close(); } } 

En API 19+ puede utilizar Java Automatic Resource Management:

 public static void copy(File src, File dst) throws IOException { try (InputStream in = new FileInputStream(src)) { try (OutputStream out = new FileOutputStream(dst)) { // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } } } 

Como alternativa, puede utilizar FileChannel para copiar un archivo. Puede ser más rápido que el método de copia de bytes al copiar un archivo grande. No puedes usarlo si tu archivo es mayor que 2 GB.

 public void copy(File src, File dst) throws IOException { FileInputStream inStream = new FileInputStream(src); FileOutputStream outStream = new FileOutputStream(dst); FileChannel inChannel = inStream.getChannel(); FileChannel outChannel = outStream.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); inStream.close(); outStream.close(); } 

Estos funcionaron bien para mí

 public static void copyFileOrDirectory(String srcDir, String dstDir) { try { File src = new File(srcDir); File dst = new File(dstDir, src.getName()); if (src.isDirectory()) { String files[] = src.list(); int filesLength = files.length; for (int i = 0; i < filesLength; i++) { String src1 = (new File(src, files[i]).getPath()); String dst1 = dst.getPath(); copyFileOrDirectory(src1, dst1); } } else { copyFile(src, dst); } } catch (Exception e) { e.printStackTrace(); } } public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.getParentFile().exists()) destFile.getParentFile().mkdirs(); if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } 

Puede ser demasiado tarde para una respuesta, pero la forma más conveniente es usar

FileUtils

static void copyFile(File srcFile, File destFile)

por ejemplo esto es lo que hice

 private String copy(String original, int copyNumber){ String copy_path = path + "_copy" + copyNumber; try { FileUtils.copyFile(new File(path), new File(copy_path)); return copy_path; } catch (IOException e) { e.printStackTrace(); } return null; } 

Aquí hay una solución que realmente cierra los flujos de entrada / salida si se produce un error durante la copia. Esta solución utiliza métodos de Apache Commons IO IOUtils para copiar y manejar el cierre de los flujos.

  public void copyFile(File src, File dst) { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = new FileOutputStream(dst); IOUtils.copy(in, out); } catch (IOException ioe) { Log.e(LOGTAG, "IOException occurred.", ioe); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(in); } } 

Si tiene permiso de root, puede copiarlo usando el siguiente código:

 void copyFile_dd(){ try { Process su; su = Runtime.getRuntime().exec("su"); String cmd = "dd if=/mnt/sdcard/test.dat of=/mnt/sdcard/test1.dat \n"+ "exit\n"; su.getOutputStream().write(cmd.getBytes()); if ((su.waitFor() != 0)) { throw new SecurityException(); } } catch (Exception e) { e.printStackTrace(); //throw new SecurityException(); } } 

O

 void copyFile_cat(){ try { Process su; su = Runtime.getRuntime().exec("su"); String cmd = "cat /mnt/sdcard/test.dat > /mnt/sdcard/test2.dat \n"+ "exit\n"; su.getOutputStream().write(cmd.getBytes()); if ((su.waitFor() != 0)) { throw new SecurityException(); } } catch (Exception e) { e.printStackTrace(); //throw new SecurityException(); } } 
  • Agregar una autoridad de certificado mediante programación al mismo tiempo que mantiene certificados SSL de sistema de Android
  • Cómo analizar JSON Array (Not Json Object) en Android
  • Autofocus de la cámara Android cuando el usuario mantiene la cámara inmóvil
  • Crear una imagen que se puede hacer clic en un GridView en Android
  • Establecer la elipse de título de actividad a la mitad?
  • Advertencia incorrecta de Lint de Android sobre recursos no utilizados
  • ¿Cómo descargar una parte de un archivo de URL en android?
  • Alternativas a java en android
  • Android - los cálculos con el tiempo transcurrido en el cronómetro
  • ¿Cuál es la manera más eficiente de ordenar simultáneamente tres ArrayLists en Java
  • DialogFragment.show cuelga la aplicación
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.