从内部存储器文件读取数据时,Android“找不到源”

时间:2013-11-26 12:59:46

标签: android

我正在尝试读取内部存储器文件(todoItems_file.txt)上的一些已保存数据。

在调试期间,while循环只读取文件的第二行,然后它读取null但是此时它不能结束循环。我收到了很多未找到的消息来源。

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_todo);

    lvItems = (ListView) findViewById(R.id.lvItems);
    items = new ArrayList<String>();
    itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
    lvItems.setAdapter(itemsAdapter);


    createDataFile();       

    File file = getFilesDir();
    String dir_path = file.getPath();
    String line = "";
    //----------------------------------------- read saved items from data file
    try {
        FileInputStream fis =new FileInputStream(dir_path + "/" + file_name); 
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader br= new BufferedReader(isr); 

        while(br.readLine() != "null"){
            line = br.readLine();
            items.add(line);

        }
        br.close();
        isr.close();
        fis.close();
        //String vv = 
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}
public void createDataFile(){
    try {

        FileOutputStream out = openFileOutput(file_name, Context.MODE_PRIVATE | Context.MODE_WORLD_READABLE); 
        OutputStreamWriter osw = new OutputStreamWriter(out);

        osw.append("first" + "\r\n");
        osw.append("sec" + "\r\n");

        osw.flush();
        osw.close();
        out.close();

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

3 个答案:

答案 0 :(得分:0)

这似乎不对:

while(br.readLine() != "null")

尝试不用引号:

while(br.readLine() != null)

答案 1 :(得分:0)

问题:您正在每次迭代中读取两行,因为每次迭代调用readLine()两次。

    while(br.readLine() != "null"){ // 1st invocation
        line = br.readLine(); // 2nd invocation
        items.add(line);
    }

解决方案:每次迭代只应调用readLine()一次,并将其返回值存储在字符串变量中,如下所示:

   String line;  
  // read every line, one at a time from the file into the line variable   
  while((line = br.readLine()) != null){  
     items.add(line)      
  }

答案 2 :(得分:0)

替换

while(br.readLine() != "null"){
    line = br.readLine();
    items.add(line);
}

使用:

String line;
while((line = br.readLine()) != null){
    items.add(line); 
}