關於Android Assets讀取檔案為File對象

來源:互聯網
上載者:User

標籤:leo   exception   available   其他   trace   搜尋   tput   apk   java   

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

 

關於Android Assets讀取檔案為File對象

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.