Java 如何从内存中读取文件并为对象分配变量
我有一个方法,理论上应该读取位于模拟器内部内存中的文本文件,并将新行后面的每一行分配给它的相关变量,然后将对象放入hashmap,我的意思是。文本文件格式如下所示:Java 如何从内存中读取文件并为对象分配变量,java,android,Java,Android,我有一个方法,理论上应该读取位于模拟器内部内存中的文本文件,并将新行后面的每一行分配给它的相关变量,然后将对象放入hashmap,我的意思是。文本文件格式如下所示: John Doe 3.0 Jane Doe 3.4 诸如此类,你就明白了。所以我想要下面的方法 public void updateList(Context context) { try { FileInputStream fis = context.openFileInput("stud
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())代码>返回为空,我在这里做错了什么?我将映射定义为soprivate HashMap studentBag=new HashMap()我调用onResume()
上的updateList()
方法,检查是否有学生在其他活动中被添加或删除
@Override
protected void onResume() {
super.onResume();
updateList(this);
}
这可能不是您所期望的(来自String.valueOf docs):如果参数为null,则为等于“null”的字符串;因此,您的检查==null
永远不会为真。您好,当您在文件上执行读/写时,使用JSON格式支持杰克逊库,这将有助于您更容易地形成数据对象。<代码>读取位于模拟器内部内存中的文本文件 >您认为模拟器的内部存储器是什么?资产
getFilesDir()
或getexternalfilesdir()
?你是怎么把文件放在那里的?见: