java - 如何从内存中读取文件并将变量分配给对象
问题描述
我有一个方法,理论上应该读取位于模拟器内部存储器中的文本文件,并将新行之后的每一行分配给其受尊重的变量,然后将对象放入哈希图中,这就是我的意思。文本文件格式如下:
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);
}
解决方案
推荐阅读
- javascript - Gmail 插件使用文本输入创建单选组
- swiftui - HStack NavigationLink 在 Form 可点击区域小
- javascript - JavaScript 参数在箭头函数中使用但未在本地范围内的任何位置声明 - Twilio 函数
- javascript - 将 TypeScript 与 NodeJS 和 Express 结合使用
- javascript - 当 2D 数组中的元素在 react native expo 中发生变化时重新渲染页面
- android - 使用 NoActionBar 主题时显示操作栏
- flutter - 使用 Firebase 托管部署的 Flutter Web 不尊重 Safari 中的刷新
- android-studio - 当我尝试添加两个editext时,应用程序不断崩溃
- url - URL 编码 +(加号)计算为空格
- ios - SwiftUI:扩展/收缩列表单元格