android - visual - vs2017 15.9 3
如何將android Path字符串轉換為Assets文件夾中的文件? (3)
AFAIK資產目錄中的文件無法解壓縮。 相反,它們直接從APK(ZIP)文件中讀取。
所以,你真的不能製作期望文件接受資產'文件'的東西。
相反,您必須提取資產並將其寫入單獨的文件,如Dumitru建議:
File f = new File(getCacheDir()+"/m1.map");
if (!f.exists()) try {
InputStream is = getAssets().open("m1.map");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
fos.close();
} catch (Exception e) { throw new RuntimeException(e); }
mapView.setMapFile(f.getPath());
我需要知道assets文件夾上文件的字符串路徑 ,因為我使用的是需要接收字符串路徑的map api,我的地圖必須存儲在assets文件夾中
這是我正在嘗試的代碼:
MapView mapView = new MapView(this);
mapView.setClickable(true);
mapView.setBuiltInZoomControls(true);
mapView.setMapFile("file:///android_asset/m1.map");
setContentView(mapView);
"file:///android_asset/m1.map"
因為地圖未加載。
這是存儲在我的資產文件夾中的文件m1.map的正確字符串路徑文件?
謝謝
編輯Dimitru:此代碼不起作用,它在is.read(buffer);
上失敗is.read(buffer);
使用IOException
try {
InputStream is = getAssets().open("m1.map");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {throw new RuntimeException(e);}
只是添加Jacek的完美解決方案。 如果你想在Kotlin做這件事,它不會馬上工作。 相反,你會想要使用這個:
@Throws(IOException::class)
fun getSplashVideo(context: Context): File {
val cacheFile = File(context.cacheDir, "splash_video")
try {
val inputStream = context.assets.open("splash_video")
val outputStream = FileOutputStream(cacheFile)
try {
inputStream.copyTo(outputStream)
} finally {
inputStream.close()
outputStream.close()
}
} catch (e: IOException) {
throw IOException("Could not open splash_video", e)
}
return cacheFile
}
請查看SDK附帶的API示例中的ReadAsset.java。
try {
InputStream is = getAssets().open("read_asset.txt");
// We guarantee that the available method returns the total
// size of the asset... of course, this does mean that a single
// asset can't be more than 2 gigs.
int size = is.available();
// Read the entire asset into a local byte buffer.
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
// Convert the buffer into a string.
String text = new String(buffer);
// Finally stick the string into the text view.
TextView tv = (TextView)findViewById(R.id.text);
tv.setText(text);
} catch (IOException e) {
// Should never happen!
throw new RuntimeException(e);
}