Nemin
Nemin

Reputation: 2037

How to make a file object of a file in the drawable or raw folder?

I want to bundle an image with my application. I am planing to keep the image in the drawable or the raw folder. I wanted to know how to make a File object of this image?

Something like this:

File file = new File("fileurl");

Thank you.

Upvotes: 2

Views: 1560

Answers (2)

Hiren Patel
Hiren Patel

Reputation: 52810

Can you please try this one ?

try {
       File mFile=new File("my file name");
       InputStream inputStream = getResources().openRawResource(R.drawable.ic_launcher);
       OutputStream out=new FileOutputStream(mFile);
       byte buf[]=new byte[1024];
       int len;
       while((len=inputStream.read(buf))>0)
           out.write(buf,0,len);
           out.close();
        inputStream.close();
      }catch (Exception e){
         e.printStackTrace();
      }

Hope this will help you.

Upvotes: 1

reidzeibel
reidzeibel

Reputation: 1632

If you put your image resource inside your Raw folder within your workspace, you can access it inside your class by using :

getResources.openRawResources(R.raw.resource_id)

EDIT :

the above code will return an inputStream, to convert it to file, try this one :

inputStream = getResources.openRawResources(R.raw.resource_id)`
// write the inputStream to a FileOutputStream
File file = new File("fileurl");
outputStream = new FileOutputStream(file);

int read = 0;
byte[] bytes = new byte[1024];

while ((read = inputStream.read(bytes)) != -1) {
       outputStream.write(bytes, 0, read);
}
outputStream.close();
inputStream.close();

Upvotes: 0

Related Questions