Cómo hacer referencia a un archivo en carpeta sin procesar en Android
Solo quiero crear un objeto File como este
File myImageFile = new File ("image1") ;
- ¿Quieres animar Marker en cada 10 segundos en google map?
- Crash casting AndroidKeyStoreRSAPrivateKey a RSAPrivateKey
- Contactos de AndroidContratar y crear en varias versiones de SDK
- ¿Hay una manera de configurar la altura y el contenido de ajuste al mismo tiempo en android?
- Android no escribirá nueva línea en el archivo de texto
Pero me está dando la excepción de FileNotFoundException
¿Cómo puedo hacer referencia a un archivo dentro de mi carpeta en bruto
EDIT: En realidad yo quería hacer algo como esto
MultipartEntity multipartEntity= new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addPart("uploaded", new FileBody(new File("myimage")));
- GridView Obtener el elemento en el tacto
- No se pudo resolver: com.google.android.gms: play-services-gcm: 7.5.
- Cómo utilizar Iniciar sesión en Android
- Advertencia incorrecta de Lint de Android sobre recursos no utilizados
- ¿Dónde obtener streaming (en directo) de vídeo y audio desde una aplicación de ejemplo de cámara para Android?
- No se puede convertir el objeto Subclase en cuerpo de solicitud json en Retrofit 2.0 con GsonConverterFactory
- GetExternalStorageDirectory no funciona
- Stackoverflow en Android 2.3.3 Sólo dispositivos
Aquí hay 2 funciones. Uno para leer de RAW y uno de los activos
/** * Method to read in a text file placed in the res/raw directory of the * application. The method reads in all lines of the file sequentially. */ public static void readRaw(Context ctx,int res_id) { InputStream is = ctx.getResources().openRawResource(res_id); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr, 8192); // 2nd arg is buffer // size // More efficient (less readable) implementation of above is the // composite expression /* * BufferedReader br = new BufferedReader(new InputStreamReader( * this.getResources().openRawResource(R.raw.textfile)), 8192); */ try { String test; while (true) { test = br.readLine(); // readLine() returns null if no more lines in the file if (test == null) break; } isr.close(); is.close(); br.close(); } catch (IOException e) { e.printStackTrace(); } }
Y de la carpeta de activos
/** * Read a file from assets * * @return the string from assets */ public static String getQuestions(Context ctx,String file_name) { AssetManager assetManager = ctx.getAssets(); ByteArrayOutputStream outputStream = null; InputStream inputStream = null; try { inputStream = assetManager.open(file_name); outputStream = new ByteArrayOutputStream(); byte buf[] = new byte[1024]; int len; try { while ((len = inputStream.read(buf)) != -1) { outputStream.write(buf, 0, len); } outputStream.close(); inputStream.close(); } catch (IOException e) { } } catch (IOException e) { } return outputStream.toString(); }
Generalmente se accede a los archivos a través de getResources (). OpenRawResource (R.id._your_id). Si necesita una referencia de archivo, una opción es copiarla en el almacenamiento interno:
File file = new File(this.getFilesDir() + File.separator + "DefaultProperties.xml"); try { InputStream inputStream = resources.openRawResource(R.id._your_id); FileOutputStream fileOutputStream = new FileOutputStream(file); byte buf[]=new byte[1024]; int len; while((len=inputStream.read(buf))>0) { fileOutputStream.write(buf,0,len); } fileOutputStream.close(); inputStream.close(); } catch (IOException e1) {}
Ahora usted tiene un File
que puede acceder a cualquier lugar que lo necesite.
Puede abrirlo como InputStream, no sé si es posible como un archivo:
int rid = resources.getIdentifier(packageName + ":raw/" + fileName, null, null); //get the file as a stream InputStrea is = resources.openRawResource(rid);
Puede utilizar InputStreamBody en lugar de FileBody para que pueda utilizarlo de esta manera:
InputStream inputStream = resources.openRawResource(R.raw.yourresource); MultipartEntity multipartEntity= new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addPart("uploaded", new InputStreamBody(inputStream));
- ¿Por qué Android utiliza Ints en vez de Enums?
- ¿Cómo inserto una imagen en una actividad con android studio?