Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/189.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Android中从资产返回文件对象?_Android_Android Assets - Fatal编程技术网

如何在Android中从资产返回文件对象?

如何在Android中从资产返回文件对象?,android,android-assets,Android,Android Assets,我想从Assets文件夹返回文件对象。在类似问题的回答中,它返回了InputStream类对象,但我不想阅读内容 我试图解释的是,assests文件夹中有一个example.eg文件。我需要将此文件声明为文件file=新文件(路径)尝试以下操作: try { BufferedReader r = new BufferedReader(new InputStreamReader(getAssets().open("example.csv"))); StringBuilder content

我想从Assets文件夹返回文件对象。在类似问题的回答中,它返回了InputStream类对象,但我不想阅读内容

我试图解释的是,assests文件夹中有一个example.eg文件。我需要将此文件声明为
文件file=新文件(路径)

尝试以下操作:

try {
  BufferedReader r = new BufferedReader(new InputStreamReader(getAssets().open("example.csv")));
  StringBuilder content = new StringBuilder();
  String line;
  while ((line = r.readLine()) != null) {
                content(line);
  }
} catch (IOException e) {
  e.printStackTrace();
}

您可以直接使用InputStream创建文件

AssetManager am = getAssets();
InputStream inputStream = am.open(file:///android_asset/myfoldername/myfilename);
File file = createFileFromInputStream(inputStream);

private File createFileFromInputStream(InputStream inputStream) {

   try{
      File f = new File(my_file_name);
      OutputStream outputStream = new FileOutputStream(f);
      byte buffer[] = new byte[1024];
      int length = 0;

      while((length=inputStream.read(buffer)) > 0) {
        outputStream.write(buffer,0,length);
      }

      outputStream.close();
      inputStream.close();

      return f;
   }catch (IOException e) {
         //Logging exception
   }

return null;
}

据我所知,资产不像其他资产那样是可正常访问的文件。 我过去常常将它们复制到内部存储,然后使用它们。 以下是它的基本思想:

    final AssetManager assetManager = getAssets();
    try {
        for (final String asset : assetManager.list("")) {
            final InputStream inputStream = assetManager.open(asset);
            // ...
        }
    }
    catch (IOException e) {
        e.printStackTrace();
    }

可能是@MikeBrianOlivera的重复,这只是示例!