我试图通过将每个整数保存在内部存储中文件的新行中来在我的应用程序中保存整数列表。为了检索它,我逐行读取它并将每个行值(解析为整数)放入我的整数列表中。我知道数据库更适合这种东西,但这应该可以。
我现在尝试了很长一段时间,但它似乎从来没有奏效。尝试阅读时,我总是得到一个空指针异常。我记录了“行”,它给出了它应该具有的值。但
保存一个 id,将其添加为新字符串:
private void saveToFavorites(Integer saveFav) {
String favstr = String.valueOf(saveFav);
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(openFileOutput("favorites", MODE_WORLD_WRITEABLE)));
writer.newLine();
writer.append((favstr));
System.out.println(" added to favs :"+ saveFav);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
以及阅读方法:
@SuppressWarnings("null")
private List<Integer> readFileFromInternalStorage() {
List<Integer> favs = null;
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(openFileInput("favorites")));
String line;
while ((line = input.readLine()) != null) {
System.out.println("readFileFromInternalStorage line value: "+ line );
favs.add(Integer.parseInt(line));
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("readFileFromInternalStorage: fail" );
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return favs;
}
这是在其他活动中。我认为它会工作,但它显然没有。回读时,logline: System.out.println("readFileFromInternalStorage line value: "+ line ); 显示 line 的值等于最后添加的 id 和一个空行,而不是其他行。所以逐行保存失败。同样,当将其解析为整数时,它会失败,这很奇怪,因为它只是一个数字。
08-01 12:29:54.190: I/System.out(1540): readFileFromInternalStorage line value:
08-01 12:29:54.190: I/System.out(1540): readFileFromInternalStorage line value: 301
有谁知道我需要改变什么?