獲取assets目錄下檔案的路徑
阿新 • • 發佈:2018-11-05
關於這個問題網上很多回答都是轉自下面的內容
第二種方法看程式碼就知道不靠譜,第一種方法感覺在後面就是不適用了。
下面是我自己做的路徑獲取程式碼:
File image = getFileStreamPath("image.jpg");
File second = getFileStreamPath("second.jpg");
Log.i(TAG, "onCreate: =path=" + image.getAbsolutePath());
Log.i(TAG, "onCreate: =paht="+second.getAbsolutePath());
File absoluteFile = image.getAbsoluteFile();
if (absoluteFile.exists()) {
Log.i(TAG, "onCreate: =檔案存在=");
} else {
Log.i(TAG, "onCreate: =檔案不存在=");
}
執行之後效果如下:
打印出來的log:
11-15 20:09:45.770 26473-26473/? I/=minwenping=: onCreate: =path=/data/user/0/com.example.administrator.hotfixdemo/files/image.jpg
11-15 20:09:45.770 26473-26473/? I/=minwenping=: onCreate: =paht=/data/user/0/com.example.administrator.hotfixdemo/files/second.jpg
11-15 20:09:45.770 26473-26473/? I/=minwenping=: onCreate: =檔案存在=
本來是系統從assetManager這個類中獲取路徑,結果返回的是目錄下檔名,從原始碼註釋中看出,這個方法容易魚目混珠,只是返回檔名,路徑讓我們自己去拼接
AssetManager assets = getResources().getAssets();
try {
String[] contents = assets.list("content");
Log.i(TAG, "onCreate: =assets content下面檔案="+contents[0]);
} catch (IOException e) {
e.printStackTrace ();
}
/**
* Return a String array of all the assets at the given path.
*
* @param path A relative path within the assets, i.e., "docs/home.html".
*
* @return String[] Array of strings, one for each asset. These file
* names are relative to 'path'. You can open the file by
* concatenating 'path' and a name in the returned string (via
* File) and passing that to open().
*
* @see #open
*/