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 AssetManagerto read a Filefrom the res/rawdirectory with an InputStream, but for my special use case I need a FileInputStream. The reason I need a FileInputStreamspecifically is because I need to get the FileChannelobject 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 Filefrom 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 FileInputStreamto a Filein the res/rawdirectory?
有没有一种方法,我可以得到FileInputStream一个File在res/raw目录中?
回答by Xaver Kapeller
You can get a FileInputStreamto a resource in your assets like this:
您可以FileInputStream像这样获取资产中的资源:
AssetFileDescriptor fileDescriptor = assetManager.openFd(fileName);
FileInputStream stream = fileDescriptor.createInputStream();
The fileNameyou supply to openFd()should be the relative path to the asset, the same fileNameyou would supply to open().
在fileName您提供的openFd()应该是资产的相对路径,同样fileName你会提供给open()。
Alternatively you can also create the FileInputStreamlike this:
或者,您也可以创建FileInputStream这样的:
AssetFileDescriptor assetFileDescriptor = assetManager.openFd(fileName);
FileDescriptor fileDescriptor = assetFileDescriptor.getFileDescriptor();
FileInputStream stream = new FileInputStream(fileDescriptor);

