How to reference a File in raw folder in Android

waseemwk picture waseemwk · Mar 17, 2012 · Viewed 31.3k times · Source

I just want to create a File object like this

File myImageFile = new File ("image1") ;

but it is giving me exception of FileNotFoundException
How can i reference a file inside my raw Folder

EDIT: Actually i wanted to do something like this

MultipartEntity multipartEntity= new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); multipartEntity.addPart("uploaded", new FileBody(new File("myimage")));

Answer

Grimmace picture Grimmace · Mar 17, 2012

Generally you access the files through getResources().openRawResource(R.id._your_id). If you absolutely need a File reference to it, one option is to copy it over to internal storage:

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) {}

Now you have a File that you can access anywhere you need it.