2011-11-22 32 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); 
相關問題