How to open a file in raw folder in Android

Nemin picture Nemin · May 24, 2013 · Viewed 19.7k times · Source

I am usin MultipartEntity and I am trying to refer to the file in the raw folder. Here is the code:

MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart(new FormBodyPart("file", new FileBody(new File("test.txt"))));

The test.txt file is in my res/raw folder. When I execute the code I get the following exception : FileNotFoundException: /test.txt: open failed: ENOENT (No such file or directory)

Can anyone help me with this?

Answer

Blackbelt picture Blackbelt · May 24, 2013

Unfortunately you can not create a File object directly from the raw folder. You need to copy it or in your sdcard or inside the application`s cache.

you can retrieve the InputStream for your file this way

    InputStream in = getResources().openRawResource(R.raw.yourfile);

  try {
       int count = 0;
       byte[] bytes = new byte[32768];
       StringBuilder builder = new StringBuilder();
       while ( (count = in.read(bytes,0, 32768)) > 0) {
           builder.append(new String(bytes, 0, count));
       }

       in.close();
       reqEntity.addPart(new FormBodyPart("file", new StringBody(builder.toString())));
   } catch (IOException e) {
       e.printStackTrace();
   }