0

I have 100 text files in /res/raw folder. I want to read a file named Hello.txt among files from this folder. But the name of the file is stored in a String variable named file_name_gen which gets the name of the file to be accessed from a function defined in code. How can I pass this variable name as file name. Below is my code.

This is what i want to do but this crashes my code abruptly.

    //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();
    }

Any relevant reference or content will help. Thank you in advance.

1 Answers1

0

you can give your all the 100 text file name as f1,f2,f2.....f100 and make an arraylist and add the file name and access the arrayList via it's position and get the file name from arralist as below explain the code.

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

this is the code to read the text file from raw folder

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(); 
  • I want to pass the file name to open it. I have stored it in a variable. Just need to know how to pass a String variable as file name to open it. – Chandraman Patil Jan 23 '17 at 17:10
  • wirte the above code in a function and cast buf object to buf.toString() and return the string from function...it'll work fine... – Mahendra Dabi Jan 23 '17 at 17:44