2014-12-24 73 views
3

對不起,對於這個問題,我是一個業餘程序員。如何從資源目錄中讀取多個文件

我在我想要閱讀的項目的raw目錄中有495個文本文件。問題是,我只能用下面的代碼讀取其中的一個,但我不知道如何讀取所有文件。

請幫幫我,

try { 
    Resources res = getResources(); 
    InputStream in_s = res.openRawResource(R.raw.help); 

    byte[] b = new byte[in_s.available()]; 
    in_s.read(b); 
    txtHelp.setText(new String(b)); 
} catch (Exception e) { 
    // e.printStackTrace(); 
    txtHelp.setText("Error: can't show help."); 
} 

回答

0
  1. 閱讀所有的原始資源名稱
  2. 獲取實際的ID(int)和打開資源爲InputStream的

    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        MainActivity.context = getApplicationContext(); 
        setContentView(R.layout.activity_main); 
        Field[] fields = R.raw.class.getFields(); 
        String[] names = new String[fields.length]; 
    
        // Step 1: Read the names 
        for (int i = 0; i < fields.length; i++) { 
         names[i] = fields[i].getName(); 
        } 
        // Step 2: Read as InputStream 
        for (int i = 0 ; i < allStringsNames.length ; i++){ 
         int id = getResources().getIdentifier(names[i] , "raw", getPackageName()); 
         InputStream inputStream = getResources().openRawResource(id); 
         //Do your stuff with variable inputStream 
        } 
        } 
    
相關問題