Android: copia los recursos en el almacenamiento interno
¡Buen día!
Acabo de comenzar a desarrollar para android. En mi aplicación, necesito copiar los elementos de mi carpeta de activos en el almacenamiento interno.
- El tamaño del anuncio y el ID de la unidad de anuncio deben estar configurados antes de cargarla.
- Java.io.FileNotFoundException: Este archivo no se puede abrir como descriptor de archivo; Probablemente está comprimido
- Animación con dos interpoladores
- Creación de un ejecutable android ffmpeg
- Necesito recuperar una instancia de una actividad
He buscado mucho en SO, incluyendo esto que lo copia en el almacenamiento externo. Cómo copiar archivos de la carpeta 'assets' a sdcard?
Esto es lo que quiero lograr: Tengo un directorio ya presente en el almacenamiento interno como X> Y> Z. Necesito un archivo para ser copiado a Y y otro a Z.
¿Puede alguien ayudarme con un fragmento de código? Realmente no tengo ni idea de cómo seguir adelante sobre esto.
Perdón por mi mal ingles.
Muchas gracias.
- Cómo detener el video de Webview en android
- Android: int que en DialogInterface.OnClickListener () es -1
- ¿Cómo calcular el usuario activo en Mobile App Analytics?
- Parada de la conexión del proxy de medios de Android
- Eclipse proyecto androide siempre lauching en depuración
- calculadora no procesa dos ecuaciones de operador
- Android: ClassNotFoundException al pasar el objeto serializable a la actividad
- ¿Es imposible hacer un juego Android sin tartamudear? Me estoy volviendo loco aqui
Utilizar
String out= Environment.getExternalStorageDirectory().getAbsolutePath() + "/X/Y/Z/" ; File outFile = new File(out, Filename);
Después de la edición en su ref. Respuesta de enlace.
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); } for(String filename : files) { InputStream in = null; OutputStream out = null; try { in = assetManager.open(filename); String outDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/X/Y/Z/" ; File outFile = new File(outDir, filename); out = new FileOutputStream(outFile); copyFile(in, out); in.close(); in = null; out.flush(); out.close(); out = null; } catch(IOException e) { Log.e("tag", "Failed to copy asset file: " + filename, e); } } } 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); } }
Hola chicos hice algo como esto. Que le permite copiar toda la estructura de directorios para copiar desde Android AssetManager 🙂
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"); } } }
Prueba este código abajo
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); } 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); in.close(); in = null; out.flush(); out.close(); out = null; } catch(IOException e) { Log.e("tag", "Failed to copy asset file: " + filename, e); } } } 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); } }
public void addFilesToSystem(String sysName, String intFil, Context c){ //sysName is the name of the file we have in the android os //intFil is the name of the internal file file = new File(path, sysName + ".txt"); if(!file.exists()){ path.mkdirs(); try { AssetManager am = c.getAssets(); InputStream is = am.open(intFil); OutputStream os = new FileOutputStream(file); byte[] data = new byte[is.available()]; is.read(data); os.write(data); is.close(); os.close(); Toast t = Toast.makeText(c, "Making file: " + file.getName() + ". One time action", Toast.LENGTH_LONG); t.show(); //Update files for the user to use MediaScannerConnection.scanFile(c, new String[] {file.toString()}, null, new MediaScannerConnection.OnScanCompletedListener() { public void onScanCompleted(String path, Uri uri) { // TODO Auto-generated method stub } }); } catch (IOException e) { Toast t = Toast.makeText(c, "Error: " + e.toString() + ". One time action", Toast.LENGTH_LONG); t.show(); e.printStackTrace(); } } }
Para agregar un archivo, llame a addFilesToSystem ("this_file_is_in_the_public_system", "this_file_is_in_the_assets_folder", contexto / este contexto es si no tiene el método en la carpeta Activity /
Espero eso ayude
Puede utilizar el método Envrionment # getDataDirectory para ello. Dará la ruta del directorio de datos de la memoria interna de almacenamiento. Esto es generalmente donde se almacenan todos los datos relacionados con la aplicación.
Alternativamente, si desea almacenar en el directorio raíz, puede utilizar el método Environment # getRootDirectory para ello.
- ¿Cómo comprobar la disponibilidad de espacio en el almacenamiento externo?
- Gradle excluir plugin en proyecto principal para subproyecto (s) específico (s)