How to open a file in raw folder in Android

20,538

Solution 1

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();
   }

Solution 2

You can put the file in the /res/raw directory, where the file will be indexed and is accessible by an id in the R file:

InputStream is = getResources().openRawResource(R.raw.test);
System.out.println(is);
Share:
20,538
Nemin
Author by

Nemin

Updated on June 21, 2020

Comments

  • Nemin
    Nemin almost 4 years

    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?

  • Nemin
    Nemin almost 11 years
    Is it possible to create a file object from the drawable folder? Also, How can i use InputStream in the addPart() method?
  • Blackbelt
    Blackbelt almost 11 years
    does your file contains text?
  • Blackbelt
    Blackbelt almost 11 years
    use StringBody. Read the content of the file in a String
  • Nemin
    Nemin almost 11 years
    The problem is that I want to get the file object so that I can uplaod it on the server. I have not written the servlet code and cannot change it either. When I try to use InputStream the server gives me 400 status code (Bad request). Is there any other why I can get the reference of the file? It need not be in the raw folder.
  • enadun
    enadun almost 11 years
    Oh... Do you want a reference to your file ? Then why don't you use just R.raw.test (create 'raw' inside 'res' folder)
  • Nemin
    Nemin almost 11 years
    The new File() asks for an URL. Can you suggest me how to user the ID R.raw.test in passing the URL?
  • enadun
    enadun almost 11 years
    Uri myFile = Uri.parse("android.resource://com.package.project/raw/filena‌​me"); NOTE give your package and project names correctly