2017-01-23 81 views
0

我在/ RES /原始文件夹100个的文本文件。我想从这个文件夹中的文件中读取一个名为Hello.txt的文件。但该文件的名称存储在一个字符串变量命名file_name_gen其获取要在代码中定义的函数访问的文件的名称。我怎样才能传递这个变量名作为文件名。以下是我的代码。如何打开文本文件,它的名字存储在Android的字符串?

这就是我想做的事情,但这个突然崩溃我的代码。

//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

'这个崩溃我的代码代码'曾经说过一句话'crash'你必须添加一个堆栈跟踪 –

回答

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(); 
+0

我想通过文件名来打开它。我将它存储在一个变量中。只需要知道如何传递一个字符串变量作为文件名来打开它。 –

+0

WIRTE在功能上面的代码和投BUF对象buf.toString(),并返回从函数的字符串...它会工作得很好... –

相关问题