Context:
You have a URI to a resource which is placed in the raw directory inside the Android resources directory, res. Say you want to take that raw resource(let’s say it’s an image) and add it to an attachment using FIleBody to a MultiPartEntity. Both these classes are available in the Apache HTTP Components library. FileBody will only allow you to give it a File object in it’s constructor. Certainly, you are stuck as you have the URI to an Android raw resource, and CANNOT create a File object out of it.
So what’s the solution? Reflection.
private File getFileFromRawResource(Uri rUri) { String uri = rUri.toString(); String fn; // I've only tested this with raw resources if (uri.contains("/raw/")) { // Try to get the resource name String[] parts = uri.split("/"); fn = parts[parts.length - 1]; } else { return null; } // Notice that I've hard-coded the file extension to .jpg // I was working with getting a File object of a JPEG image from my raw resources String dest = Environment.getExternalStorageDirectory() + "/image.jpg"; try { // Use reflection to get resource ID of the raw resource // as we need to get an InputStream to it // getResources(),openRawResource() takes only a resource ID R.raw r = new R.raw(); Field frame = R.raw.class.getDeclaredField(fn); frame.setAccessible(true); int id = (Integer) frame.get(r); // Get the InputStream InputStream inputStream = getResources().openRawResource(id); FileOutputStream fileOutputStream = new FileOutputStream(dest); // IOUtils is a class from Apache Commons IO // It writes an InputStream to an OutputStream IOUtils.copy(inputStream, fileOutputStream); fileOutputStream.close(); return new File(dest); } catch (NoSuchFieldException e) { Log.e("MyApp", "NoSuchFieldException in getFileFromRawResource()"); } catch (IllegalAccessException e) { Log.e("MyApp", "IllegalAccessException in getFileFromRawResource()"); } catch (FileNotFoundException e) { Log.e("MyApp", "FileNotFoundException in getFileFromRawResource()"); } catch (IOException e) { Log.e("MyApp", "IOException in getFileFromRawResource()"); } return null; }
The code is pretty much self-explanatory. Drop a comment if you have any questions/doubts.