4

I am wondering about how to get random access to an android asset. The AssetManager class offers the method "open" and you can pass AssetManager.ACCESS_RANDOM to that method. The documentation says, you kann seek forward and backward in the file (especially seeking backward is what I need), whenn passing ACCESS_RANDOM. However, the open method always returns an InputStream object, no matter which access mode was requested. So my question is: how can I call seek methods on that InputStream that does not offer such methods? To which class must I cast the InputStream? I've been searching the web for that problem for some time now, but I could not find anything that helped me.

Thanks!

Paul H
  • 600
  • 1
  • 5
  • 13

2 Answers2

0

Looking at this source, the method open(String fileName, int accessMode) actually returns an AssetInputStream.

I did not test it, but you might be able to cast the InputStream of the open() method to an AssetInputStream, which offers the methods you are looking for. In particular, the skip(long n) method will allow you to skip the first n bytes of the file.

You can give it a try and see if it works.

EDIT: if you are looking for a completely random access to the file, I guess it's just not possible. See this answer for more information.

Community
  • 1
  • 1
Sebastiano
  • 12,289
  • 6
  • 47
  • 80
  • 1
    Thanks for the answer, but I don't see any "seek"-like methods even in `AssetInputStream`. Or are there some tomatoes on my eyes? :D – Paul H Mar 07 '14 at 22:55
  • I'm sorry, for a moment I forgot that you also wanted to be able to go backwards. I've edited my answer accordingly. – Sebastiano Mar 08 '14 at 08:31
0

Copy assets file to cache/temp, then open it for random access, something like this (add errors/write error handling)

File outputDir = context.getCacheDir();
File destFile = new File(outputDir, "asset_filename");
OutputStream dest = new FileOutputStream(destFile, true);
InputStream src = context.getAssets().open("asset_directory/asset_filename", ACCESS_STREAMING);
byte[] buff = new byte[100*1024];
for(;;)
{
    int cnt = src.read(buff);
    if(cnt <= 0)
        break;
    dest.write(buff, 0, cnt);
}
dest.flush();
dest.close();
assetFile = new RandomAccessFile(destFile, "r");
Lukasz F
  • 1
  • 2