2014-12-24 76 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 
        } 
        } 
    
相关问题