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?
- Destruye la sesión de Nuance
- "Clase no encontrada" al ejecutar pruebas JUnit desde IntelliJ IDEA (Android)
- Asegúrese de que el nombre de clase existe, es público y tiene un constructor vacío para fragmento público con nombre de clase y constructor vacío
- Skype comienza a marcar y se bloquea después de 2 segundos - Android
- Cambiar String-Array en Strings.xml a ArrayList
¿Cuál es la mejor manera de hacerlo?
- No se pudo encontrar la clase 'android.support.v4.widget.SwipeRefreshLayout'
- Accediendo simultáneamente a diferentes miembros del mismo objeto en Java
- ¿Por qué debería importarme las excepciones detectadas en Java?
- Proyecto de Android que utiliza httpclient -> http.client (apache), método post / get
- Implementar seguridad a nivel de firma en los servicios de Android con más de una firma permitida
- ¿Cómo puedo incluir dependencias en mi biblioteca de Android?
- Android: Redireccionar a otra actividad después del retardo
- Android / gradle: no puede utilizar el repositorio
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(); } }
- Actualizar la altura de TextView después de establecer la fuente con setTypeface en Android
- Cómo obtener nombre de recurso de cadena por su valor