65

文字列パスを受け取る必要があるマップ API を使用しており、マップを assets フォルダーに保存する必要があるため、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 の編集: このコードは機能しません。IOException で失敗しますis.read(buffer);

        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);}
4

4 に答える 4

100

私の知る限り、資産ディレクトリ内のファイルは解凍されません。代わりに、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());
于 2011-12-12T13:33:03.413 に答える
10

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);
    }
于 2011-12-12T13:18:14.067 に答える
4

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
}
于 2017-06-29T15:55:10.097 に答える