Android 如何将资产文件夹中的文件路径传递给文件(字符串路径)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11820142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass a file path which is in assets folder to File(String path)?
提问by akd
Possible Duplicate:
Android - How to determine the Absolute path for specific file from Assets?
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?
我正在尝试将文件传递给 File(String path) 类。有没有办法在assets文件夹中找到文件的绝对路径并将其传递给File()。我尝试file:///android_asset/myfoldername/myfilename
作为路径字符串,但没有用。任何的想法?
回答by yugidroid
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.
AFAIK,您不能File
从资产文件创建一个,因为它们存储在 apk 中,这意味着没有资产文件夹的路径。
But, you can try to create that File
using a buffer and the AssetManager
(it provides access to an application's raw asset files).
但是,您可以尝试File
使用缓冲区和AssetManager
(它提供对应用程序的原始资产文件的访问)来创建它。
Try to do something like:
尝试执行以下操作:
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;
}
Let me know about your progress.
让我知道你的进展。
回答by nEx.Software
Unless you unpack them, assets remain inside the apk. Accordingly, there isn't a path you can feed into a File. The path you've given in your question will work with/in a WebView, but I think that's a special case for WebView.
除非您解压它们,否则资产会保留在 apk 中。因此,没有可以输入文件的路径。您在问题中给出的路径将在 WebView 中使用/在 WebView 中使用,但我认为这是 WebView 的特例。
You'll need to unpack the file or use it directly.
您需要解压缩文件或直接使用它。
If you have a Context, you can use context.getAssets().open("myfoldername/myfilename");
to open an InputStream on the file. With the InputStream you can use it directly, or write it out somewhere (after which you can use it with File).
如果您有 Context,则可以使用context.getAssets().open("myfoldername/myfilename");
来打开文件上的 InputStream。通过 InputStream,您可以直接使用它,或者将其写在某处(之后您可以将它与 File 一起使用)。