Jak uzyskać ciąg ścieżki Androida do pliku w folderze zasoby?

Muszę znać string path do pliku w folderze assets, ponieważ używam API map, które musi odbierać ścieżkę łańcuchową, a Moje mapy muszą być przechowywane w folderze assets

Oto kod, który próbuję:

    MapView mapView = new MapView(this);
    mapView.setClickable(true);
    mapView.setBuiltInZoomControls(true);
    mapView.setMapFile("file:///android_asset/m1.map");
    setContentView(mapView);

Coś jest nie tak z "file:///android_asset/m1.map" ponieważ mapa nie jest ładowana.

Który jest prawidłowym plikiem ścieżki do pliku m1.Mapa przechowywana w folderze Moje zasoby?

Dzięki

Edycja dla Dimitru: ten kod nie działa, nie działa na is.read(buffer); z 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);}
Author: ppreetikaa, 2011-12-12

4 answers

AFAIK pliki w katalogu assets nie zostaną rozpakowane. Zamiast tego są one odczytywane bezpośrednio z pliku APK (ZIP).

Tak naprawdę nie można sprawić, by rzeczy, które oczekują pliku zaakceptowały plik zasobu.

Zamiast tego będziesz musiał wyodrębnić zasób i zapisać go do oddzielnego pliku, jak sugeruje 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());
 95
Author: Jacob Nordfalk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-07 20:02:29

Możesz użyć tej metody.

    public static File getRobotCacheFile(Context context) throws IOException {
        File cacheFile = new File(context.getCacheDir(), "robot.png");
        try {
            InputStream inputStream = context.getAssets().open("robot.png");
            try {
                FileOutputStream outputStream = new FileOutputStream(cacheFile);
                try {
                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = inputStream.read(buf)) > 0) {
                        outputStream.write(buf, 0, len);
                    }
                } finally {
                    outputStream.close();
                }
            } finally {
                inputStream.close();
            }
        } catch (IOException e) {
            throw new IOException("Could not open robot png", e);
        }
        return cacheFile;
    }

Należy nigdy nie używać InputStream.dostępny () w takich przypadkach. Zwraca tylko bajty, które są buforowane. Metoda z .funkcja dostępna nigdy nie będzie działać z większymi plikami i nie będzie działać na niektórych urządzeniach.

W Kotlinie (; D):

@Throws(IOException::class)
fun getRobotCacheFile(context: Context): File = File(context.cacheDir, "robot.png")
    .also {
        it.outputStream().use { cache -> context.assets.open("robot.png").use { it.copyTo(cache) } }
    }
 13
Author: Jacek Marchwicki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-08 16:59:01

Spójrz na ReadAsset.java z próbek API dołączonych do zestawu SDK.

       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);
    }
 10
Author: Dumitru Hristov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-12-12 13:18:14

Żeby dodać do tego idealne rozwiązanie Jacka. Jeśli próbujesz to zrobić w Kotlinie, to nie zadziała natychmiast. Zamiast tego będziesz chciał użyć tego:

@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
}
 4
Author: CheesusCrust,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-29 15:55:10