En mi aplicación, quiero guardar una copia de un determinado archivo con un nombre diferente (que obtengo del usuario)
¿Realmente necesito abrir el contenido del archivo y escribirlo en otro archivo?
¿Cual es la mejor manera de hacerlo?
Para copiar un archivo y guardarlo en su ruta de destino, puede usar el método a continuación.
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 usar la gestión automática de recursos de Java:
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); } } } }Alternativamente, puede usar FileChannel para copiar un archivo. Puede ser más rápido que el método de copia de bytes al copiar un archivo grande. Sin embargo, no puede usarlo si su archivo tiene más de 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(); }Extensión Kotlin para ello.
fun File.copyTo(file: File) { inputStream().use { input -> file.outputStream().use { output -> input.copyTo(output) } } }