30

Possible Duplicate:
Android - How to determine the Absolute path for specific file from Assets?

I am trying to pass a file to File(String path) class. Is there a way to find absolute path of the file in assets folder and pass it to File(). I tried file:///android_asset/myfoldername/myfilename as path string but it didnt work. Any idea?

Community
  • 1
  • 1
akd
  • 6,538
  • 16
  • 70
  • 112

2 Answers2

55

AFAIK, you can't create a File from an assets file because these are stored in the apk, that means there is no path to an assets folder.

But, you can try to create that File using a buffer and the AssetManager (it provides access to an application's raw asset files).

Try to do something like:

AssetManager am = getAssets();
InputStream inputStream = am.open("myfoldername/myfilename");
File file = createFileFromInputStream(inputStream);

private File createFileFromInputStream(InputStream inputStream) {

   try{
      File f = new File(my_file_name);
      OutputStream outputStream = new FileOutputStream(f);
      byte buffer[] = new byte[1024];
      int length = 0;

      while((length=inputStream.read(buffer)) > 0) {
        outputStream.write(buffer,0,length);
      }

      outputStream.close();
      inputStream.close();

      return f;
   }catch (IOException e) {
         //Logging exception
   }

   return null;
}

Let me know about your progress.

Kirill Bubochkin
  • 5,868
  • 2
  • 31
  • 50
yugidroid
  • 6,640
  • 2
  • 30
  • 45
9

Unless you unpack them, assets remain inside the apk. Accordingly, there isn't a path you can feed into a File. The path you've given in your question will work with/in a WebView, but I think that's a special case for WebView.

You'll need to unpack the file or use it directly.

If you have a Context, you can use context.getAssets().open("myfoldername/myfilename"); to open an InputStream on the file. With the InputStream you can use it directly, or write it out somewhere (after which you can use it with File).

nEx.Software
  • 6,782
  • 1
  • 26
  • 34
  • Thanks a lot. it helped. but the code below saves me from writing the file somewhere. – akd Aug 06 '12 at 02:45
  • @akd which code below? Are you talking about yugidroid code? Because that code is creating a new file is it not? – b.lyte Mar 07 '16 at 22:47
  • this was back in 2012. I can't remember really. but I guess I am talking about yugidroid code as there are only 2 answers. And I guess as yugidroid stated that it provides access to an application's raw asset files instead of creating a file. – akd Mar 07 '16 at 23:38