關於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;
     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM