標籤: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對象