Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: how do I create File object from asset file?

I have a text file in the assets folder that I need to turn into a File object (not into InputStream). When I tried this, I got "no such file" exception:

String path = "file:///android_asset/datafile.txt";
URL url = new URL(path);
File file = new File(url.toURI());  // Get exception here

Can I modify this to get it to work?

By the way, I sort of tried to "code by example" looking at the following piece of code elsewhere in my project that references an HTML file in the assets folder

public static Dialog doDialog(final Context context) {
WebView wv = new WebView(context);      
wv.loadUrl("file:///android_asset/help/index.html");

I do admit that I don't fully understand the above mechanism so it's possible that what I am trying to do can't work.

Thx!

like image 705
I Z Avatar asked May 01 '12 18:05

I Z


2 Answers

You cannot get a File object directly from an asset, because the asset is not stored as a file. You will need to copy the asset to a file, then get a File object on your copy.

like image 74
CommonsWare Avatar answered Oct 16 '22 21:10

CommonsWare


You cannot get a File object directly from an asset.

First, get an inputStream from your asset using for example AssetManager#open

Then copy the inputStream :

    public static void writeBytesToFile(InputStream is, File file) throws IOException{
    FileOutputStream fos = null;
    try {   
        byte[] data = new byte[2048];
        int nbread = 0;
        fos = new FileOutputStream(file);
        while((nbread=is.read(data))>-1){
            fos.write(data,0,nbread);               
        }
    }
    catch (Exception ex) {
        logger.error("Exception",ex);
    }
    finally{
        if (fos!=null){
            fos.close();
        }
    }
}
like image 32
Laurent B Avatar answered Oct 16 '22 22:10

Laurent B