首页 > 解决方案 > 如何从内存中读取文件并将变量分配给对象

问题描述

我有一个方法,理论上应该读取位于模拟器内部存储器中的文本文件,并将新行之后的每一行分配给其受尊重的变量,然后将对象放入哈希图中,这就是我的意思。文本文件格式如下:

John
Doe
3.0

Jane
Doe
3.4

等等,你明白了。所以我想要以下方法

public void updateList(Context context) {
        try {
            FileInputStream fis = context.openFileInput("students.txt");
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            String line;
            Student student = new Student();
            while ((line = br.readLine()) != null) {
                if (!line.trim().isEmpty()) {
                    if (student.getFirstName() == null) {
                        student.setFirstName(line.trim());
                    } else if (student.getLastName() == null) {
                        student.setLastName(line.trim());
                    } else if (String.valueOf(student.getGpa()) == null) {
                        student.setGpa(Double.parseDouble(line.trim()));
                        studentBag.put(student.getFirstName(), student);
                    } else {
                        student = new Student();
                    }
                }
            }
            System.out.println(studentBag.toString()); //print out to check contents of map
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

将新行之后的第一行分配给 firstName,将第二行分配给 lastName,将第三行分配给 gpa。每个空行表示一个新Student对象的开始。然而System.out.println(studentBag.toString());回来是空的,我在这里做错了什么?我有这样定义的地图private HashMap<String, Student> studentBag = new HashMap<>();,我这样调用updateList()ononResume()方法,以检查是否在其他活动中添加或删除了任何学生

@Override
    protected void onResume() {
        super.onResume();
        updateList(this);
    }

标签: javaandroid

解决方案


推荐阅读