如何将android路径字符串获取到Assets文件夹中的文件? [英] How to get the android Path string to a file on Assets folder?

查看:45
本文介绍了如何将android路径字符串获取到Assets文件夹中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道资产文件夹上文件的字符串路径,因为我使用的地图 API 需要接收字符串路径,而且我的地图必须存储在资产文件夹中

I need to know the string path to a file on assets folder, because I'm using a map API that needs to receive a string path, and my maps must be stored on assets folder

这是我正在尝试的代码:

This is the code i'm trying:

    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" 出了点问题,因为地图没有被加载.

Something is going wrong with "file:///android_asset/m1.map" because the map is not being loaded.

哪个是存储在我的资产文件夹中的文件 m1.map 的正确字符串路径文件?

Which is the correct string path file to the file m1.map stored on my assets folder?

谢谢

为 Dimitru 此代码不起作用,它在 is.read(buffer);IOException

EDIT for Dimitru: This code doesn't works, it fails on is.read(buffer); with 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);}

推荐答案

AFAIK 资产目录中的文件没有被解压.相反,它们是直接从 APK (ZIP) 文件中读取的.

AFAIK the files in the assets directory don't get unpacked. Instead, they are read directly from the APK (ZIP) file.

因此,您真的无法制作期望 file 接受资产文件"的东西.

So, you really can't make stuff that expects a file accept an asset 'file'.

相反,您必须像 Dumitru 建议的那样提取资产并将其写入单独的文件:

Instead, you'll have to extract the asset and write it to a seperate file, like Dumitru suggests:

  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());

这篇关于如何将android路径字符串获取到Assets文件夹中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆