关于Android Assets读取文件为File对象

/ Android / 没有评论 / 2338浏览

关于Android Assets读取文件为File对象

关于Android Assets读取文件为File对象的问题,在Assets里面放置文件,在使用的时候,一般是使用AssetManger对象,open方法获取InputStream,然后进行其他操作.

这里遇到了这样需求,直接把Assets里面文件读取为一个File对象,找了半天,没有找到这样方法,搜索了很久,发现这样是行不通的.是不能直接从asset获取然后直接转换为File对象的,因为asset被存储为apk中,除非你解压Apk文件,一般是不能找到一个Path实例化一个File对象的,这里也有特殊情况,webview可以根据asset的路径加载在asset存放的.html文件:

WebView wv = new WebView(context);      
wv.loadUrl("file:///android_asset/help/index.html");

如果需要一个File的时候,需要从新拷贝一份,把File存储在设备上,然后再使用。

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

或者直接InputStream转换为String,然后执行其他操作.

AssetManager am = getActivity().getAssets();
InputStream inputStream = am.open("chapter1/ObservableVSIterator.java");
String json = null;
try {
    int size = inputStream.available();
    byte[] buffer = new byte[size];
    inputStream.read(buffer);
    inputStream.close();
    json = new String(buffer, "UTF-8");
} catch (IOException ex) {
    ex.printStackTrace();
    return null;
}

时刻怀有一颗虔诚之心,乐于分享。知识才更有意义。