使用存储在SD卡上的文本文件填充String数组

时间:2012-03-17 12:04:40

标签: android

我的SD卡上有一个文本文件,如下所示:

TEST1

TEST2

TEST3

我想通过读取文件来填充String数组并获得如下数组:

String[] val = {"test0","test1","test2"};

这是我读取文件的方式但是如何读取每一行并填充数组? :

 public void ReadSettings(){

    try{             
           File f = new File(Environment.getExternalStorageDirectory()+"/file.txt");             
           FileInputStream fileIS = new FileInputStream(f);          
           BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));           
           String readString = new String();                

           while ((readString = buf.readLine()) != null) {

               Log.d("line: ", readString);   

           for (int i=0 ; i < 3 ; i++){
                      val[i] = readString;

            }

        } catch (FileNotFoundException e) {          
           e.printStackTrace();          
        } catch (IOException e){             
           e.printStackTrace();          
    }    
} 

这是我不幸的事情:

String[] val = {"test2","test2","test2"};

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:2)

int i = 0;
while ((readString = buf.readLine()) != null) {
    Log.d("line: ", readString);   
    val[i++] = readString;
    // u better use an ArrayList or you have to check if i < val.size
}