telefono tarjeta samsung pasar mover memoria los interna externa error como archivos ala android copy assets

android - tarjeta - ¿Cómo copiar archivos de la carpeta ''activos'' a sdcard?



error al mover archivos ala sd (18)

Tengo algunos archivos en la carpeta de assets . Necesito copiarlos todos a una carpeta como / sdcard / folder. Quiero hacer esto desde dentro de un hilo. ¿Cómo lo hago?


Aquí hay una versión mejorada para dispositivos Android actuales, diseño de método funcional para que pueda copiarlo en una clase AssetsHelper, por ejemplo;)

/** * * Info: prior to Android 2.3, any compressed asset file with an * uncompressed size of over 1 MB cannot be read from the APK. So this * should only be used if the device has android 2.3 or later running! * * @param c * @param targetFolder * e.g. {@link Environment#getExternalStorageDirectory()} * @throws Exception */ @TargetApi(Build.VERSION_CODES.GINGERBREAD) public static boolean copyAssets(AssetManager assetManager, File targetFolder) throws Exception { Log.i(LOG_TAG, "Copying files from assets to folder " + targetFolder); return copyAssets(assetManager, "", targetFolder); } /** * The files will be copied at the location targetFolder+path so if you * enter path="abc" and targetfolder="sdcard" the files will be located in * "sdcard/abc" * * @param assetManager * @param path * @param targetFolder * @return * @throws Exception */ public static boolean copyAssets(AssetManager assetManager, String path, File targetFolder) throws Exception { Log.i(LOG_TAG, "Copying " + path + " to " + targetFolder); String sources[] = assetManager.list(path); if (sources.length == 0) { // its not a folder, so its a file: copyAssetFileToFolder(assetManager, path, targetFolder); } else { // its a folder: if (path.startsWith("images") || path.startsWith("sounds") || path.startsWith("webkit")) { Log.i(LOG_TAG, " > Skipping " + path); return false; } File targetDir = new File(targetFolder, path); targetDir.mkdirs(); for (String source : sources) { String fullSourcePath = path.equals("") ? source : (path + File.separator + source); copyAssets(assetManager, fullSourcePath, targetFolder); } } return true; } private static void copyAssetFileToFolder(AssetManager assetManager, String fullAssetPath, File targetBasePath) throws IOException { InputStream in = assetManager.open(fullAssetPath); OutputStream out = new FileOutputStream(new File(targetBasePath, fullAssetPath)); byte[] buffer = new byte[16 * 1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); out.flush(); out.close(); }


Basándome en la solución de Rohith Nandakumar, hice algo propio para copiar archivos de una subcarpeta de activos (es decir, "activos / MyFolder "). Además, estoy comprobando si el archivo ya existe en sdcard antes de intentar copiarlo nuevamente.

private void copyAssets() { AssetManager assetManager = getAssets(); String[] files = null; try { files = assetManager.list("MyFolder"); } catch (IOException e) { Log.e("tag", "Failed to get asset file list.", e); } if (files != null) for (String filename : files) { InputStream in = null; OutputStream out = null; try { in = assetManager.open("MyFolder/"+filename); File outFile = new File(getExternalFilesDir(null), filename); if (!(outFile.exists())) {// File does not exist... out = new FileOutputStream(outFile); copyFile(in, out); } } catch(IOException e) { Log.e("tag", "Failed to copy asset file: " + filename, e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // NOOP } } if (out != null) { try { out.close(); } catch (IOException e) { // NOOP } } } } } private void copyFile(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int read; while((read = in.read(buffer)) != -1){ out.write(buffer, 0, read); } }


Basándome en su solución, hice algo propio para permitir subcarpetas. Alguien podría encontrar esto útil:

...

copyFileOrDir("myrootdir");

...

private void copyFileOrDir(String path) { AssetManager assetManager = this.getAssets(); String assets[] = null; try { assets = assetManager.list(path); if (assets.length == 0) { copyFile(path); } else { String fullPath = "/data/data/" + this.getPackageName() + "/" + path; File dir = new File(fullPath); if (!dir.exists()) dir.mkdir(); for (int i = 0; i < assets.length; ++i) { copyFileOrDir(path + "/" + assets[i]); } } } catch (IOException ex) { Log.e("tag", "I/O Exception", ex); } } private void copyFile(String filename) { AssetManager assetManager = this.getAssets(); InputStream in = null; OutputStream out = null; try { in = assetManager.open(filename); String newFileName = "/data/data/" + this.getPackageName() + "/" + filename; out = new FileOutputStream(newFileName); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); in = null; out.flush(); out.close(); out = null; } catch (Exception e) { Log.e("tag", e.getMessage()); } }


Buen ejemplo. Respondí mi pregunta de cómo acceder a los archivos en la carpeta de activos.

El único cambio que sugeriría es en el bucle for. El siguiente formato también funcionaría y se prefiere:

for(String filename : files) { InputStream in = null; OutputStream out = null; try { in = assetManager.open(filename); out = new FileOutputStream("/sdcard/" + filename); ... }


Con AssetManager , permite leer los archivos en los activos. Luego use el IO de Java normal para escribir los archivos en la tarjeta SD.

Google es tu amigo, busca un ejemplo.


Copie todos los archivos y directorios de activos a su carpeta!

Para copiar mejor usa apache commons io.

public void doCopyAssets() throws IOException { File externalFilesDir = context.getExternalFilesDir(null); doCopy("", externalFilesDir.getPath()); }

// ESTE ES EL METODO PRINCIPAL PARA COPIAR

private void doCopy(String dirName, String outPath) throws IOException { String[] srcFiles = assets.list(dirName);//for directory for (String srcFileName : srcFiles) { String outFileName = outPath + File.separator + srcFileName; String inFileName = dirName + File.separator + srcFileName; if (dirName.equals("")) {// for first time inFileName = srcFileName; } try { InputStream inputStream = assets.open(inFileName); copyAndClose(inputStream, new FileOutputStream(outFileName)); } catch (IOException e) {//if directory fails exception new File(outFileName).mkdir(); doCopy(inFileName, outFileName); } } } public static void closeQuietly(AutoCloseable autoCloseable) { try { if(autoCloseable != null) { autoCloseable.close(); } } catch(IOException ioe) { //skip } } public static void copyAndClose(InputStream input, OutputStream output) throws IOException { copy(input, output); closeQuietly(input); closeQuietly(output); } public static void copy(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[1024]; int n = 0; while(-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); } }


Esta es, con mucho, la mejor solución que he podido encontrar en Internet. He usado el siguiente enlace https://gist.github.com/mhasby/026f02b33fcc4207b302a60645f6e217 ,
pero tenía un solo error que solucioné y luego funciona como un amuleto. Aquí está mi código. Puedes usarlo fácilmente ya que es una clase java independiente.

public class CopyAssets { public static void copyAssets(Context context) { AssetManager assetManager = context.getAssets(); String[] files = null; try { files = assetManager.list(""); } catch (IOException e) { Log.e("tag", "Failed to get asset file list.", e); } if (files != null) for (String filename : files) { InputStream in = null; OutputStream out = null; try { in = assetManager.open(filename); out = new FileOutputStream(Environment.getExternalStorageDirectory()+"/www/resources/" + filename); copyFile(in, out); } catch(IOException e) { Log.e("tag", "Failed to copy asset file: " + filename, e); } finally { if (in != null) { try { in.close(); in = null; } catch (IOException e) { } } if (out != null) { try { out.flush(); out.close(); out = null; } catch (IOException e) { } } } } } public static void copyFile(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int read; while((read = in.read(buffer)) != -1){ out.write(buffer, 0, read); } }}

Como puede ver, simplemente cree una instancia de CopyAssets en su clase java que tenga una actividad. Ahora, esta parte es importante, en cuanto a mis pruebas e investigaciones en Internet, You cannot use AssetManager if the class has no activity . Tiene algo que ver con el contexto de la clase java.
Ahora, c.copyAssets(getApplicationContext()) es una forma fácil de acceder al método, donde c es y la instancia de la clase CopyAssets . Según mi requerimiento, permití que el programa copie todos mis archivos de recursos dentro de la carpeta de asset a /www/resources/ de mi directorio interno.
Puede encontrar fácilmente la parte en la que necesita realizar cambios en el directorio según su uso. Siéntase libre de hacerme ping si necesita ayuda.


Hay esencialmente dos formas de hacer esto.

Primero, puede usar AssetManager.open y, como lo describe Rohith Nandakumar e iterar sobre la corriente de entrada.

En segundo lugar, puede utilizar AssetManager.openFd , que le permite usar un FileChannel (que tiene el [transferTo] ( https://developer.android.com/reference/java/nio/channels/FileChannel.html#transferTo(long , long, java.nio.channels.WritableByteChannel)) y [transferFrom] ( https://developer.android.com/reference/java/nio/channels/FileChannel.html#transferFrom(java.nio.channels.ReadableByteChannel , largo largo)) métodos), para que no tenga que hacer un bucle sobre el flujo de entrada.

Voy a describir el método openFd aquí.

Compresión

Primero debe asegurarse de que el archivo se almacene sin comprimir. El sistema de empaquetado puede optar por comprimir cualquier archivo con una extensión que no esté marcada como noCompress , y los archivos comprimidos no pueden asignarse a la memoria, por lo que tendrá que confiar en AssetManager.open en ese caso.

Puede agregar una extensión ''.mp3'' a su archivo para evitar que se comprima, pero la solución adecuada es modificar su aplicación / build.gradle y agregar las siguientes líneas (para deshabilitar la compresión de archivos PDF)

aaptOptions { noCompress ''pdf'' }

Archivo de embalaje

Tenga en cuenta que el empaquetador aún puede empaquetar varios archivos en uno, por lo que no puede leer todo el archivo que AssetManager le proporciona. Debe preguntar al AssetFileDescriptor qué partes necesita.

Encontrar la parte correcta del archivo empaquetado

Una vez que haya asegurado que su archivo se almacene sin comprimir, puede usar el método AssetManager.openFd para obtener un AssetFileDescriptor , que se puede usar para obtener un FileInputStream (a diferencia de AssetManager.open , que devuelve un InputStream ) que contiene un FileChannel . También contiene el desplazamiento inicial (getStartOffset) y el tamaño (getLength) , que necesita para obtener la parte correcta del archivo.

Implementación

A continuación se muestra un ejemplo de implementación:

private void copyFileFromAssets(String in_filename, File out_file){ Log.d("copyFileFromAssets", "Copying file ''"+in_filename+"'' to ''"+out_file.toString()+"''"); AssetManager assetManager = getApplicationContext().getAssets(); FileChannel in_chan = null, out_chan = null; try { AssetFileDescriptor in_afd = assetManager.openFd(in_filename); FileInputStream in_stream = in_afd.createInputStream(); in_chan = in_stream.getChannel(); Log.d("copyFileFromAssets", "Asset space in file: start = "+in_afd.getStartOffset()+", length = "+in_afd.getLength()); FileOutputStream out_stream = new FileOutputStream(out_file); out_chan = out_stream.getChannel(); in_chan.transferTo(in_afd.getStartOffset(), in_afd.getLength(), out_chan); } catch (IOException ioe){ Log.w("copyFileFromAssets", "Failed to copy file ''"+in_filename+"'' to external storage:"+ioe.toString()); } finally { try { if (in_chan != null) { in_chan.close(); } if (out_chan != null) { out_chan.close(); } } catch (IOException ioe){} } }

Esta respuesta se basa en la respuesta de JPM .


Hola chicos, hice algo como esto. Para N-th Depth Copy Folder y Files para copiar. Lo que le permite copiar toda la estructura de directorios para copiar desde Android AssetManager :)

private void manageAssetFolderToSDcard() { try { String arg_assetDir = getApplicationContext().getPackageName(); String arg_destinationDir = FRConstants.ANDROID_DATA + arg_assetDir; File FolderInCache = new File(arg_destinationDir); if (!FolderInCache.exists()) { copyDirorfileFromAssetManager(arg_assetDir, arg_destinationDir); } } catch (IOException e1) { e1.printStackTrace(); } } public String copyDirorfileFromAssetManager(String arg_assetDir, String arg_destinationDir) throws IOException { File sd_path = Environment.getExternalStorageDirectory(); String dest_dir_path = sd_path + addLeadingSlash(arg_destinationDir); File dest_dir = new File(dest_dir_path); createDir(dest_dir); AssetManager asset_manager = getApplicationContext().getAssets(); String[] files = asset_manager.list(arg_assetDir); for (int i = 0; i < files.length; i++) { String abs_asset_file_path = addTrailingSlash(arg_assetDir) + files[i]; String sub_files[] = asset_manager.list(abs_asset_file_path); if (sub_files.length == 0) { // It is a file String dest_file_path = addTrailingSlash(dest_dir_path) + files[i]; copyAssetFile(abs_asset_file_path, dest_file_path); } else { // It is a sub directory copyDirorfileFromAssetManager(abs_asset_file_path, addTrailingSlash(arg_destinationDir) + files[i]); } } return dest_dir_path; } public void copyAssetFile(String assetFilePath, String destinationFilePath) throws IOException { InputStream in = getApplicationContext().getAssets().open(assetFilePath); OutputStream out = new FileOutputStream(destinationFilePath); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } public String addTrailingSlash(String path) { if (path.charAt(path.length() - 1) != ''/'') { path += "/"; } return path; } public String addLeadingSlash(String path) { if (path.charAt(0) != ''/'') { path = "/" + path; } return path; } public void createDir(File dir) throws IOException { if (dir.exists()) { if (!dir.isDirectory()) { throw new IOException("Can''t create directory, a file is in the way"); } } else { dir.mkdirs(); if (!dir.isDirectory()) { throw new IOException("Unable to create directory"); } } }

Al final crea una asynctask:

private class ManageAssetFolders extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... arg0) { manageAssetFolderToSDcard(); return null; } }

Llámalo de tu actividad:

new ManageAssetFolders().execute();


La solución anterior no funcionó debido a algunos errores:

  • la creación del directorio no funcionó
  • Los activos devueltos por Android también contienen tres carpetas: imágenes, sonidos y webkit.
  • Forma adicional de tratar con archivos grandes: agregue la extensión .mp3 al archivo en la carpeta de activos en su proyecto y durante la copia, el archivo de destino estará sin la extensión .mp3

Aquí está el código (dejé las declaraciones de registro, pero puedes soltarlas ahora):

final static String TARGET_BASE_PATH = "/sdcard/appname/voices/"; private void copyFilesToSdCard() { copyFileOrDir(""); // copy all files in assets folder in my project } private void copyFileOrDir(String path) { AssetManager assetManager = this.getAssets(); String assets[] = null; try { Log.i("tag", "copyFileOrDir() "+path); assets = assetManager.list(path); if (assets.length == 0) { copyFile(path); } else { String fullPath = TARGET_BASE_PATH + path; Log.i("tag", "path="+fullPath); File dir = new File(fullPath); if (!dir.exists() && !path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit")) if (!dir.mkdirs()) Log.i("tag", "could not create dir "+fullPath); for (int i = 0; i < assets.length; ++i) { String p; if (path.equals("")) p = ""; else p = path + "/"; if (!path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit")) copyFileOrDir( p + assets[i]); } } } catch (IOException ex) { Log.e("tag", "I/O Exception", ex); } } private void copyFile(String filename) { AssetManager assetManager = this.getAssets(); InputStream in = null; OutputStream out = null; String newFileName = null; try { Log.i("tag", "copyFile() "+filename); in = assetManager.open(filename); if (filename.endsWith(".jpg")) // extension was added to avoid compression on APK file newFileName = TARGET_BASE_PATH + filename.substring(0, filename.length()-4); else newFileName = TARGET_BASE_PATH + filename; out = new FileOutputStream(newFileName); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); in = null; out.flush(); out.close(); out = null; } catch (Exception e) { Log.e("tag", "Exception in copyFile() of "+newFileName); Log.e("tag", "Exception in copyFile() "+e.toString()); } }

EDITAR: Corregido un fuera de lugar ";" que estaba lanzando un error sistemático "no se pudo crear dir".


Modificación leve de la respuesta anterior para copiar una carpeta de forma recursiva y para adaptarse a un destino personalizado.

public void copyFileOrDir(String path, String destinationDir) { AssetManager assetManager = this.getAssets(); String assets[] = null; try { assets = assetManager.list(path); if (assets.length == 0) { copyFile(path,destinationDir); } else { String fullPath = destinationDir + "/" + path; File dir = new File(fullPath); if (!dir.exists()) dir.mkdir(); for (int i = 0; i < assets.length; ++i) { copyFileOrDir(path + "/" + assets[i], destinationDir + path + "/" + assets[i]); } } } catch (IOException ex) { Log.e("tag", "I/O Exception", ex); } } private void copyFile(String filename, String destinationDir) { AssetManager assetManager = this.getAssets(); String newFileName = destinationDir + "/" + filename; InputStream in = null; OutputStream out = null; try { in = assetManager.open(filename); out = new FileOutputStream(newFileName); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); in = null; out.flush(); out.close(); out = null; } catch (Exception e) { Log.e("tag", e.getMessage()); } new File(newFileName).setExecutable(true, false); }


Modificado esta respuesta SO por @DannyA

private void copyAssets(String path, String outPath) { AssetManager assetManager = this.getAssets(); String assets[]; try { assets = assetManager.list(path); if (assets.length == 0) { copyFile(path, outPath); } else { String fullPath = outPath + "/" + path; File dir = new File(fullPath); if (!dir.exists()) if (!dir.mkdir()) Log.e(TAG, "No create external directory: " + dir ); for (String asset : assets) { copyAssets(path + "/" + asset, outPath); } } } catch (IOException ex) { Log.e(TAG, "I/O Exception", ex); } } private void copyFile(String filename, String outPath) { AssetManager assetManager = this.getAssets(); InputStream in; OutputStream out; try { in = assetManager.open(filename); String newFileName = outPath + "/" + filename; out = new FileOutputStream(newFileName); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); out.flush(); out.close(); } catch (Exception e) { Log.e(TAG, e.getMessage()); } }

Preparativos

en src/main/assets agregue la carpeta con el nombre fold

Uso

File outDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString()); copyAssets("fold",outDir.toString());

En el directorio externo, encuentre todos los archivos y directorios que están dentro de los recursos de plegado


Sé que esto ha sido respondido pero tengo una forma un poco más elegante de copiar desde el directorio de activos a un archivo en la tarjeta SD. No requiere ningún bucle "for", sino que utiliza secuencias de archivos y canales para realizar el trabajo.

(Nota) Si utiliza cualquier tipo de archivo comprimido, APK, PDF, ... es posible que desee cambiar el nombre de la extensión del archivo antes de insertarlo en el activo y luego cambiar el nombre una vez que lo copie en la tarjeta SD)

AssetManager am = context.getAssets(); AssetFileDescriptor afd = null; try { afd = am.openFd( "MyFile.dat"); // Create new file to copy into. File file = new File(Environment.getExternalStorageDirectory() + java.io.File.separator + "NewFile.dat"); file.createNewFile(); copyFdToFile(afd.getFileDescriptor(), file); } catch (IOException e) { e.printStackTrace(); }

Una forma de copiar un archivo sin tener que recorrerlo.

public static void copyFdToFile(FileDescriptor src, File dst) throws IOException { FileChannel inChannel = new FileInputStream(src).getChannel(); FileChannel outChannel = new FileOutputStream(dst).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }


Según la respuesta de Yoram Cohen, aquí hay una versión que admite directorios de destino no estáticos.

Invoque con copyFileOrDir(getDataDir(), "") para escribir en la carpeta de almacenamiento de aplicaciones internas / data / data / pkg_name /

  • Soporta subcarpetas.
  • Admite directorio de destino personalizado y no estático
  • Evita copiar "imágenes", etc. carpetas de activos falsos como

    private void copyFileOrDir(String TARGET_BASE_PATH, String path) { AssetManager assetManager = this.getAssets(); String assets[] = null; try { Log.i("tag", "copyFileOrDir() "+path); assets = assetManager.list(path); if (assets.length == 0) { copyFile(TARGET_BASE_PATH, path); } else { String fullPath = TARGET_BASE_PATH + "/" + path; Log.i("tag", "path="+fullPath); File dir = new File(fullPath); if (!dir.exists() && !path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit")) if (!dir.mkdirs()) Log.i("tag", "could not create dir "+fullPath); for (int i = 0; i < assets.length; ++i) { String p; if (path.equals("")) p = ""; else p = path + "/"; if (!path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit")) copyFileOrDir(TARGET_BASE_PATH, p + assets[i]); } } } catch (IOException ex) { Log.e("tag", "I/O Exception", ex); } } private void copyFile(String TARGET_BASE_PATH, String filename) { AssetManager assetManager = this.getAssets(); InputStream in = null; OutputStream out = null; String newFileName = null; try { Log.i("tag", "copyFile() "+filename); in = assetManager.open(filename); if (filename.endsWith(".jpg")) // extension was added to avoid compression on APK file newFileName = TARGET_BASE_PATH + "/" + filename.substring(0, filename.length()-4); else newFileName = TARGET_BASE_PATH + "/" + filename; out = new FileOutputStream(newFileName); byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); in = null; out.flush(); out.close(); out = null; } catch (Exception e) { Log.e("tag", "Exception in copyFile() of "+newFileName); Log.e("tag", "Exception in copyFile() "+e.toString()); } }


Si alguien más tiene el mismo problema, así es como lo hice.

private void copyAssets() { AssetManager assetManager = getAssets(); String[] files = null; try { files = assetManager.list(""); } catch (IOException e) { Log.e("tag", "Failed to get asset file list.", e); } if (files != null) for (String filename : files) { InputStream in = null; OutputStream out = null; try { in = assetManager.open(filename); File outFile = new File(getExternalFilesDir(null), filename); out = new FileOutputStream(outFile); copyFile(in, out); } catch(IOException e) { Log.e("tag", "Failed to copy asset file: " + filename, e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { // NOOP } } if (out != null) { try { out.close(); } catch (IOException e) { // NOOP } } } } } private void copyFile(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int read; while((read = in.read(buffer)) != -1){ out.write(buffer, 0, read); } }

Referencia: Mover archivo usando Java


Usando algunos de los conceptos en las respuestas a esta pregunta, escribí una clase llamada AssetCopier para hacer que copiar /assets/ simple. Está disponible en github y se puede acceder con jitpack.io :

new AssetCopier(MainActivity.this) .withFileScanning() .copy("tocopy", destDir);

Consulte github para obtener más detalles.


prueba esto es mucho más simple, esto te ayudará a:

// Open your local db as the input stream InputStream myInput = _context.getAssets().open(YOUR FILE NAME); // Path to the just created empty db String outFileName =SDCARD PATH + YOUR FILE NAME; // Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); // transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } // Close the streams myOutput.flush(); myOutput.close(); myInput.close();


import android.app.Activity; import android.content.Intent; import android.content.res.AssetManager; import android.net.Uri; import android.os.Environment; import android.os.Bundle; import android.util.Log; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); copyReadAssets(); } private void copyReadAssets() { AssetManager assetManager = getAssets(); InputStream in = null; OutputStream out = null; String strDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+ File.separator + "Pdfs"; File fileDir = new File(strDir); fileDir.mkdirs(); // crear la ruta si no existe File file = new File(fileDir, "example2.pdf"); try { in = assetManager.open("example.pdf"); //leer el archivo de assets out = new BufferedOutputStream(new FileOutputStream(file)); //crear el archivo copyFile(in, out); in.close(); in = null; out.flush(); out.close(); out = null; } catch (Exception e) { Log.e("tag", e.getMessage()); } Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + File.separator + "Pdfs" + "/example2.pdf"), "application/pdf"); startActivity(intent); } private void copyFile(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } }

Cambiar partes de código como estas:

out = new BufferedOutputStream(new FileOutputStream(file));

el ejemplo anterior es para Pdfs, en caso de ejemplo .txt

FileOutputStream fos = new FileOutputStream(file);