如何将资产文件夹中的文件路径传递给文件(字符串路径)? [英] How to pass a file path which is in assets folder to File(String path)?

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

问题描述

可能的重复:
Android - 如何确定绝对路径对于资产中的特定文件?

我正在尝试将文件传递给 File(String path) 类.有没有办法在assets文件夹中找到文件的绝对路径并将其传递给File().我尝试将 file:///android_asset/myfoldername/myfilename 作为路径字符串,但没有用.有什么想法吗?

I am trying to pass a file to File(String path) class. Is there a way to find absolute path of the file in assets folder and pass it to File(). I tried file:///android_asset/myfoldername/myfilename as path string but it didnt work. Any idea?

推荐答案

AFAIK,您不能从资产文件创建 File,因为这些文件存储在 apk 中,这意味着没有资产文件夹的路径.

AFAIK, you can't create a File from an assets file because these are stored in the apk, that means there is no path to an assets folder.

但是,您可以尝试使用缓冲区和 AssetManager(它提供对应用程序原始资产文件的访问).

But, you can try to create that File using a buffer and the AssetManager (it provides access to an application's raw asset files).

尝试执行以下操作:

AssetManager am = getAssets();
InputStream inputStream = am.open("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;
}

让我知道你的进展.

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

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