我在/ res / raw文件夹中有100个文本文件。我想在此文件夹中的文件中读取名为Hello.txt的文件。但是文件的名称存储在名为file_name_gen的String变量中,该变量从代码中定义的函数中获取要访问的文件的名称。如何将此变量名称作为文件名传递。以下是我的代码。
这就是我想要做的事,但这突然使我的代码崩溃了。
//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();
}
任何相关的参考或内容都会有所帮助。提前谢谢。
答案 0 :(得分:0)
你可以将你的所有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;
}
这是从原始文件夹
读取文本文件的代码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();