{"id":1457,"date":"2013-07-26T22:25:43","date_gmt":"2013-07-26T16:55:43","guid":{"rendered":"http:\/\/judepereira.com\/blog\/?p=1457"},"modified":"2014-04-19T18:48:27","modified_gmt":"2014-04-19T13:18:27","slug":"how-to-get-a-file-object-of-an-android-raw-resource-using-reflection","status":"publish","type":"post","link":"https:\/\/judepereira.com\/blog\/how-to-get-a-file-object-of-an-android-raw-resource-using-reflection\/","title":{"rendered":"How to get a File object of an Android raw resource using reflection"},"content":{"rendered":"<p><strong>Context:<\/strong><\/p>\n<p>You have a URI to a resource which is placed in the <em>raw<\/em> directory inside the Android resources directory, <em>res.<\/em>\u00a0Say you want to take that raw resource(let&#8217;s say it&#8217;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\u00a0in it&#8217;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.<\/p>\n<p>&nbsp;<\/p>\n<p>So what&#8217;s the solution? Reflection.<\/p>\n<p>[code language=&#8221;java&#8221;]<br \/>\n    private File getFileFromRawResource(Uri rUri) {<br \/>\n        String uri = rUri.toString();<br \/>\n        String fn;<br \/>\n        \/\/ I&#8217;ve only tested this with raw resources<br \/>\n        if (uri.contains(&#8220;\/raw\/&#8221;)) {<br \/>\n            \/\/ Try to get the resource name<br \/>\n            String[] parts = uri.split(&#8220;\/&#8221;);<br \/>\n            fn = parts[parts.length &#8211; 1];<br \/>\n        } else {<br \/>\n            return null;<br \/>\n        }<br \/>\n        \/\/ Notice that I&#8217;ve hard-coded the file extension to .jpg<br \/>\n        \/\/ I was working with getting a File object of a JPEG image from my raw resources<br \/>\n        String dest = Environment.getExternalStorageDirectory() + &#8220;\/image.jpg&#8221;;<br \/>\n        try {<br \/>\n            \/\/ Use reflection to get resource ID of the raw resource<br \/>\n            \/\/ as we need to get an InputStream to it<br \/>\n            \/\/ getResources(),openRawResource() takes only a resource ID<br \/>\n            R.raw r = new R.raw();<br \/>\n            Field frame = R.raw.class.getDeclaredField(fn);<br \/>\n            frame.setAccessible(true);<br \/>\n            int id = (Integer) frame.get(r);<br \/>\n            \/\/ Get the InputStream<br \/>\n            InputStream inputStream = getResources().openRawResource(id);<br \/>\n            FileOutputStream fileOutputStream = new FileOutputStream(dest);<br \/>\n            \/\/ IOUtils is a class from Apache Commons IO<br \/>\n            \/\/ It writes an InputStream to an OutputStream<br \/>\n            IOUtils.copy(inputStream, fileOutputStream);<br \/>\n            fileOutputStream.close();<br \/>\n            return new File(dest);<br \/>\n        } catch (NoSuchFieldException e) {<br \/>\n            Log.e(&#8220;MyApp&#8221;, &#8220;NoSuchFieldException in getFileFromRawResource()&#8221;);<br \/>\n        } catch (IllegalAccessException e) {<br \/>\n            Log.e(&#8220;MyApp&#8221;, &#8220;IllegalAccessException in getFileFromRawResource()&#8221;);<br \/>\n        } catch (FileNotFoundException e) {<br \/>\n            Log.e(&#8220;MyApp&#8221;, &#8220;FileNotFoundException in getFileFromRawResource()&#8221;);<br \/>\n        } catch (IOException e) {<br \/>\n            Log.e(&#8220;MyApp&#8221;, &#8220;IOException in getFileFromRawResource()&#8221;);<br \/>\n        }<br \/>\n        return null;<br \/>\n    }<br \/>\n[\/code]<\/p>\n<p>The code is pretty much self-explanatory. Drop a comment if you have any questions\/doubts.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Context: You have a URI to a resource which is placed in the raw directory inside the Android resources directory, res.\u00a0Say you want to take that raw resource(let&#8217;s say it&#8217;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 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[401,52],"tags":[556,464,465,336,463,461,462,460,467,466],"class_list":["post-1457","post","type-post","status-publish","format-standard","hentry","category-android","category-code","tag-android","tag-file","tag-from","tag-get","tag-java","tag-raw-resource","tag-reflection","tag-resource","tag-resource-uri","tag-uri"],"aioseo_notices":[],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_shortlink":"https:\/\/wp.me\/pqtyx-nv","jetpack-related-posts":[{"id":1713,"url":"https:\/\/judepereira.com\/blog\/a-letter-to-tim-cook-regarding-ios-10-with-love-for-apple\/","url_meta":{"origin":1457,"position":0},"title":"A letter to Tim Cook regarding iOS 10, with love for Apple","author":"Jude Pereira","date":"June 17, 2016","format":false,"excerpt":"Tim, iOS has always been known for it's user interface, until recently. Your new take on notifications have not only made them very loud, and unsettling, but do not flow with the entire look and feel of Apple: No Mr. Tim, no. My notifications aren't waiting for me. They're crying\u2026","rel":"","context":"In &quot;life!&quot;","block_context":{"text":"life!","link":"https:\/\/judepereira.com\/blog\/category\/living-a-wonder\/"},"img":{"alt_text":"No Mr. Tim, no. My notifications will not be waiting for me. They're crying out for my attention.","src":"https:\/\/i0.wp.com\/judepereira.com\/blog\/wp-content\/uploads\/Screen-Shot-2016-06-17-at-08.49.59-614x1024.png?resize=350%2C200&ssl=1","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/judepereira.com\/blog\/wp-content\/uploads\/Screen-Shot-2016-06-17-at-08.49.59-614x1024.png?resize=350%2C200&ssl=1 1x, https:\/\/i0.wp.com\/judepereira.com\/blog\/wp-content\/uploads\/Screen-Shot-2016-06-17-at-08.49.59-614x1024.png?resize=525%2C300&ssl=1 1.5x"},"classes":[]},{"id":1786,"url":"https:\/\/judepereira.com\/blog\/contributing-to-go-in-54-days\/","url_meta":{"origin":1457,"position":1},"title":"Contributing to Go in 54 days","author":"Jude Pereira","date":"October 8, 2017","format":false,"excerpt":"With absolutely zero knowledge of Go 54 days ago, I decided to contribute to the Go project. Why? Put simply, I was bored. The thrill of learning something new, and contributing to a massive OSS project like Go caught my attention. How? Find an issue that's tagged as\u00a0HelpWanted. There's a\u2026","rel":"","context":"In &quot;another snippet | code&quot;","block_context":{"text":"another snippet | code","link":"https:\/\/judepereira.com\/blog\/category\/code\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1778,"url":"https:\/\/judepereira.com\/blog\/letstuneup-a-music-chart-with-arjit-singh-in-the-lead\/","url_meta":{"origin":1457,"position":2},"title":"LetsTuneup: A music chart with Arjit Singh in the lead","author":"Jude Pereira","date":"April 28, 2017","format":false,"excerpt":"LetsTuneup has grown tremendously, and with it, we've introduced new features too. We identified that a few of our users couldn't use the app to it's full extent because they didn't have music on their devices. We've solved that. Users can now pick their favourite artists, powered by a location\u2026","rel":"","context":"In &quot;android&quot;","block_context":{"text":"android","link":"https:\/\/judepereira.com\/blog\/category\/code\/android\/"},"img":{"alt_text":"Arjit Singh in the lead, with Eminem, Linking Park, Coldplay and Pink Floyd following close","src":"https:\/\/i0.wp.com\/judepereira.com\/blog\/wp-content\/uploads\/artists.png?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":1734,"url":"https:\/\/judepereira.com\/blog\/why-matchbox-and-how-it-connects-people-through-music\/","url_meta":{"origin":1457,"position":3},"title":"Why Matchbox, and how it connects people through music","author":"Jude Pereira","date":"January 21, 2017","format":false,"excerpt":"There's no doubt that music defines us. It influences our moods, for example, making us happy by releasing a chemical named dopamine. It can affect what we wear, what we eat, and perhaps even who we enjoy being together with. It affects\u00a0our thought process too (it's well known that ambient\u2026","rel":"","context":"In &quot;android&quot;","block_context":{"text":"android","link":"https:\/\/judepereira.com\/blog\/category\/code\/android\/"},"img":{"alt_text":"Matchbox showing the top 10 artists","src":"https:\/\/i0.wp.com\/judepereira.com\/blog\/wp-content\/uploads\/IMG_7195-300x210.png?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":1685,"url":"https:\/\/judepereira.com\/blog\/compile-less-on-the-fly-for-your-exploded-war-in-intellij\/","url_meta":{"origin":1457,"position":4},"title":"Compile LESS on the fly for your exploded WAR in IntelliJ","author":"Jude Pereira","date":"February 5, 2016","format":false,"excerpt":"At CleverTap, we've recently started using LESS for dynamic CSS. While it has it's upsides, the biggest downside\u00a0was that most of our developers couldn't use the hot deploy feature for their local deployments. After an hour or so, we came up with a neat solution. \u00a0 There are two parts\u2026","rel":"","context":"In &quot;another snippet | code&quot;","block_context":{"text":"another snippet | code","link":"https:\/\/judepereira.com\/blog\/category\/code\/"},"img":{"alt_text":"External Tool configuration for compiling LESS files before deployment","src":"https:\/\/i0.wp.com\/judepereira.com\/blog\/wp-content\/uploads\/Screen-Shot-2016-02-05-at-01.32.45-1024x494.png?resize=350%2C200","width":350,"height":200,"srcset":"https:\/\/i0.wp.com\/judepereira.com\/blog\/wp-content\/uploads\/Screen-Shot-2016-02-05-at-01.32.45-1024x494.png?resize=350%2C200 1x, https:\/\/i0.wp.com\/judepereira.com\/blog\/wp-content\/uploads\/Screen-Shot-2016-02-05-at-01.32.45-1024x494.png?resize=525%2C300 1.5x"},"classes":[]},{"id":893,"url":"https:\/\/judepereira.com\/blog\/coloured-varlogmessages-at-tty12\/","url_meta":{"origin":1457,"position":5},"title":"Coloured \/var\/log\/messages at tty12","author":"Jude Pereira","date":"April 26, 2011","format":false,"excerpt":"Reading logs could never become any more easier, at just a keystroke, you have your logs displayed where you want, in some fancy colour. They look great too. TTY's can be accessed by pressing Alt + Ctrl + F[1 - 12] simultaneously. In the following, you'll get a decent, colourized\u2026","rel":"","context":"In &quot;another snippet | code&quot;","block_context":{"text":"another snippet | code","link":"https:\/\/judepereira.com\/blog\/category\/code\/"},"img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/judepereira.com\/blog\/wp-json\/wp\/v2\/posts\/1457","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/judepereira.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/judepereira.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/judepereira.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/judepereira.com\/blog\/wp-json\/wp\/v2\/comments?post=1457"}],"version-history":[{"count":3,"href":"https:\/\/judepereira.com\/blog\/wp-json\/wp\/v2\/posts\/1457\/revisions"}],"predecessor-version":[{"id":1460,"href":"https:\/\/judepereira.com\/blog\/wp-json\/wp\/v2\/posts\/1457\/revisions\/1460"}],"wp:attachment":[{"href":"https:\/\/judepereira.com\/blog\/wp-json\/wp\/v2\/media?parent=1457"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/judepereira.com\/blog\/wp-json\/wp\/v2\/categories?post=1457"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/judepereira.com\/blog\/wp-json\/wp\/v2\/tags?post=1457"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}