RandomAccessFile的Android中的原始资源文件 [英] RandomAccessFile in Android raw resource file
问题描述
我试图从没有成功的Android资源目录的原始资源文件中创建一个RandomAccessFile的对象。
I tried to create a RandomAccessFile object from a raw resource file in android resource directory without success.
我只能够从原始资源文件中的InputStream对象。
I'm only able to get a inputstream object from raw resource file.
getResources().openRawResource(R.raw.file);
是否有可能建立从原材料资源文件RandomAccessFile的对象或是否需要坚持的InputStream?
Is it possible to create a RandomAccessFile object from raw asset file or Do I need to stick with inputstream?
推荐答案
这是根本不可能寻求前进和后退的输入流没有缓冲之间的一切到内存中。这可以是非常昂贵的,并且不是用于阅读一些任意大小的(二进制)文件一个可扩展的解决方案。
It's simply not possible to seek forward and back in an input stream without buffering everything in between into memory. That can be extremely costly, and isn't a scalable solution for reading a (binary) file of some arbitrary size.
您说的没错:理想情况下,人们会使用的RandomAccessFile
,但是从资源读取提供的输入流来代替。在上述评论提到的建议是使用输入流,以将文件写入到SD卡,并随机地从那里访问该文件。你可以考虑写文件到一个临时目录,阅读它,并在使用后删除它:
You're right: ideally, one would use a RandomAccessFile
, but reading from the resources provides an input stream instead. The suggestion mentioned in the comments above is to use the input stream to write the file to the SD card, and randomly access the file from there. You could consider writing the file to a temporary directory, reading it, and deleting it after use:
String file = "your_binary_file.bin";
AssetFileDescriptor afd = null;
FileInputStream fis = null;
File tmpFile = null;
RandomAccessFile raf = null;
try {
afd = context.getAssets().openFd(file);
long len = afd.getLength();
fis = afd.createInputStream();
// We'll create a file in the application's cache directory
File dir = context.getCacheDir();
dir.mkdirs();
tmpFile = new File(dir, file);
if (tmpFile.exists()) {
// Delete the temporary file if it already exists
tmpFile.delete();
}
FileOutputStream fos = null;
try {
// Write the asset file to the temporary location
fos = new FileOutputStream(tmpFile);
byte[] buffer = new byte[1024];
int bufferLen;
while ((bufferLen = fis.read(buffer)) != -1) {
fos.write(buffer, 0, bufferLen);
}
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {}
}
}
// Read the newly created file
raf = new RandomAccessFile(tmpFile, "r");
// Read your file here
} catch (IOException e) {
Log.e(TAG, "Failed reading asset", e);
} finally {
if (raf != null) {
try {
raf.close();
} catch (IOException e) {}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {}
}
if (afd != null) {
try {
afd.close();
} catch (IOException e) {}
}
// Clean up
if (tmpFile != null) {
tmpFile.delete();
}
}
这篇关于RandomAccessFile的Android中的原始资源文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!