android从包中获取文件列表

时间:2013-02-01 13:33:11

标签: android android-resources

如何获取.json配置文件的所有列表,这些配置文件不在SD卡上,而是在我的包中?图像上的Bellow显示了我想要访问的文件夹中的文件。这个想法如下:当应用程序启动时,我想获取配置文件列表,它们的路径,并显示给测试人员选择连接到哪个服务器。我怎样才能做到这一点?我一直在寻找PackageManagerAssetManager,但没有结果。

当我将文件夹配置放到文件夹资源时,这段代码会给我一个可用配置列表,但是我怎样才能获得完整的路径来阅读它们呢?

AssetManager am = getAssets();
String s = getPackageName();
Resources tmp = pm.getResourcesForApplication(s);
String [] arr = am.list("configs2");

snapshot

2 个答案:

答案 0 :(得分:1)

为了做类似的事情,我使用了以下命令:

InputStream is = context.getResources().openRawResource(R.raw.raw_data_file);

文件raw_data_file位于路径res/raw/raw_data_file.txt中。然后,您可以正常使用InputStream读取文件。我相信你能够对你的文件执行类似的操作,但通常我会在res(ources)文件夹中放置任何资源

答案 1 :(得分:1)

我终于解决了我的问题。这是我项目的结构: enter image description here

  1. 要从应用程序包中获取文件列表,您需要将要获取的所有文件放入assets文件夹中。这是代码:

    private ArrayList getPackageConfigList()             {                 AssetManager am = getAssets();                 String [] arr = null;                 尝试                 {                     arr = am.list(文件夹);                 }                 catch(IOException e){e.printStackTrace();}

                ArrayList<String> flist = new ArrayList<String>();
    
                for (int i=0; i<arr.length; i++)
                {
                    flist.add(PKG + arr[i]);
                    Log.d(tag, PKG+ arr[i]);
                }
    
                return flist;
            }
    
    1. 从包中读取具体文件:
    2. private String loadConfigFromPackage(String fileName)     {         AssetManager am = getAssets();         InputStream in = null;         String result = null;

      try
      {
          //open file, read to buffer, convert to string
          in = am.open(folder + "/" + fileName);
          int size = in.available();
          byte[] buffer = new byte[size];
          in.read(buffer);
          in.close();
          result = new String(buffer);
      }
      catch(IOException e)
      {
          e.printStackTrace();
      }
      finally
      {
          try
          {
              in.close();
          }
          catch(Exception ex){}
      }
      return result;
      

      }

相关问题