2011-11-22 33 views
3

我正在编写我的第一个Android应用程序,并且正在尝试读取res/raw资源文件。openRawResourceFd在Android上失败

下面的代码throws一个FileNotFound例外:

AssetFileDescriptor fd = res.openRawResourceFd(R.raw.myfile); 

,但此行的代码的工作:

InputStream stream = res.openRawResource (R.raw.myfile); 

我需要AssetFileDescriptor,以确定该文件的长度。任何想法,为什么它不工作?

+0

你有没有找到办法做到这一点? –

回答

1

移动你的MYFILE资产的文件夹,并尝试这个

try{ 
    AssetFileDescriptor descriptor = getAssets().openFd("myfile"); 
    FileDescriptor fd = descriptor.getFileDescriptor(); 
} 
catch(Exception) 
{ 

} 

或者,您可以与您的代码试试这个:

FileInputStream fdstream = res.openRawResource (R.raw.myfile); 
FileDescriptor fd = fdstream.getFD(); 

我不知道,但AssetFileDescriptor作品只有资产的文件夹。

+0

这不是永久性的解决方案,因为在资产文件夹中,我正在获取文件是压缩错误,因此我需要将文件放在原始目录中,只能看到这个线程http://stackoverflow.com/questions/6186866/java-io-filenotfoundexception -this-file-can-be-opened-as-a-file-descriptor –

+0

openRawResource返回Inputstream而不是FileInputStream – ozmank

4

你可以这样来做:需要

FileDescriptor fd = getResources().openRawResourceFd(R.raw.rawResourceId).getFileDescriptor(); 

没有try/catch块。

1

This works;

AssetFileDescriptor afd = res.openRawResourceFd(R.raw.rawResourceId); 
相关问题