Java 如何在android中打开名称存储在字符串中的文本文件?

Java 如何在android中打开名称存储在字符串中的文本文件?,java,android,file-io,Java,Android,File Io,我在/res/raw文件夹中有100个文本文件。我想从这个文件夹的文件中读取一个名为Hello.txt的文件。但文件名存储在名为file\u name\u gen的字符串变量中,该变量从代码中定义的函数获取要访问的文件名。如何将此变量名作为文件名传递。下面是我的代码 这就是我想要做的,但这会使我的代码突然崩溃 //Generate_file() is function that gives a string of filename. Here it is 'Hello' fil

我在/res/raw文件夹中有100个文本文件。我想从这个文件夹的文件中读取一个名为Hello.txt的文件。但文件名存储在名为file\u name\u gen的字符串变量中,该变量从代码中定义的函数获取要访问的文件名。如何将此变量名作为文件名传递。下面是我的代码

这就是我想要做的,但这会使我的代码突然崩溃

    //Generate_file() is function that gives a string of filename. Here it is 'Hello'

    file_name_gen=Generate_file();
    BufferedReader file_reader = new BufferedReader(new InputStreamReader(this.getResources().openRawResource(R.raw.file_name_gen)));
    while ((strlines = file_reader.readLine()) != null){
    Toast.makeText(this, strlines,Toast.LENGTH_SHORT).show();
    }

任何相关参考或内容都会有所帮助。提前谢谢。

您可以将所有100个文本文件名指定为f1、f2、f2…..f100,并制作一个arraylist,添加文件名,通过其位置访问arraylist,并从arralist中获取文件名,如下所示解释代码

   //add the name dynamically by for loop
    ArrayList<String> myfileNames=new ArrayList<>();

        for(int i=1;i<=100;i++)
        myfileNames.add("f"+i+".txt");
    //and get the name of file suppose you have selected file 20 so you can get the 
    // file name as
      Generate_file(int position)
{
       String filName=myfileNames(position);
return fileName;
}

这会使我的代码崩溃
曾经说过一个单词
crash
你必须添加StackTrace我想传递文件名来打开它。我已将其存储在一个变量中。只需要知道如何将字符串变量作为文件名传递以打开它。在函数中编写上述代码,并将buf对象强制转换为buf.toString(),然后从函数中返回字符串…它将正常工作。。。
String str="";
        StringBuffer buf = new StringBuffer();          
        InputStream is = this.getResources().openRawResource(R.raw.test);
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UNICODE"));
        if (is!=null) {                         
            while ((str = reader.readLine()) != null) { 
                buf.append(str + "\n" );
            }               
        }       
        is.close();