java 如何将 FileInputStream 获取到资产文件夹中的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30354120/
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 get FileInputStream to File in assets folder
提问by hotHead
I know how to use the AssetManager
to read a File
from the res/raw
directory with an InputStream
, but for my special use case I need a FileInputStream
. The reason I need a FileInputStream
specifically is because I need to get the FileChannel
object from it by calling getChannel()
.
我知道如何使用AssetManager
来File
从res/raw
带有的目录中读取InputStream
,但是对于我的特殊用例,我需要一个FileInputStream
. 我特别需要 a 的原因FileInputStream
是因为我需要FileChannel
通过调用getChannel()
.
This is the code I have so far, it reads the data (in my case a list of primitives) from a File
:
这是我到目前为止的代码,它从 a 读取数据(在我的例子中是原语列表)File
:
public static int[] loadByMappedBuffer(Context context, String filename) throws IOException{
FileInputStream fis = context.openFileInput(filename);
FileChannel ch = fis.getChannel();
MappedByteBuffer mbuff = ch.map(MapMode.READ_ONLY, 0, ch.size());
IntBuffer ibuff = mbuff.asIntBuffer();
int[] array = new int[ibuff.limit()];
ibuff.get(array);
fis.close();
ch.close();
return array;
}
I had tried to create File
from an Uri
, but that just results in a FileNotFoundException
:
我曾尝试File
从 an创建Uri
,但这只会导致 a FileNotFoundException
:
Uri uri = Uri.parse("android.resource://com.example.empty/raw/file");
File file = new File(uri.getPath());
FileInputStream fis = new FileInputStream(file);
Is there a way I can get a FileInputStream
to a File
in the res/raw
directory?
有没有一种方法,我可以得到FileInputStream
一个File
在res/raw
目录中?
回答by Xaver Kapeller
You can get a FileInputStream
to a resource in your assets like this:
您可以FileInputStream
像这样获取资产中的资源:
AssetFileDescriptor fileDescriptor = assetManager.openFd(fileName);
FileInputStream stream = fileDescriptor.createInputStream();
The fileName
you supply to openFd()
should be the relative path to the asset, the same fileName
you would supply to open()
.
在fileName
您提供的openFd()
应该是资产的相对路径,同样fileName
你会提供给open()
。
Alternatively you can also create the FileInputStream
like this:
或者,您也可以创建FileInputStream
这样的:
AssetFileDescriptor assetFileDescriptor = assetManager.openFd(fileName);
FileDescriptor fileDescriptor = assetFileDescriptor.getFileDescriptor();
FileInputStream stream = new FileInputStream(fileDescriptor);