2017-01-23 2 views
0

/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

당신은 f1, f2, f2 ..... f100으로 100 개의 텍스트 파일 이름을 모두주고 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

를 추가해야 crash' 단어가'내가를 전달하려는 말했다 파일 이름을여십시오. 변수에 저장했습니다. String 변수를 파일 이름으로 전달하여 여는 방법을 알아야합니다. –

+0

함수에서 위의 코드를 wirte하고 buf.toString()에 buf 객체를 형 변환하고 함수에서 문자열을 반환하면 잘 작동합니다 ... –