我試圖通過將每個整數保存在內部存儲器中的文件的新行中來保存我的應用程序中的整數列表。 爲了檢索它,我逐行讀取它,並將每個行值(整數)解析爲整數列表。 我知道一個數據庫更適合這種有點東西,但這應該工作。使用內部存儲器來保存整數列表
我想了很長一段時間,但它似乎從來沒有工作。試圖閱讀時,我總會得到一個nullpointerexception。我登錄「行」,它給了它應該有的價值。但
節省一個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); 顯示行的值等於最後添加的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
任何人都知道我需要改變什麼?
我想這個,但我得到一個錯誤:android filenotfoundexception沒有這樣的文件或目錄,爲字符串我把文件名。我應該放什麼? write_external_memory在我的清單中,那不是它 – Jasper 2012-08-01 11:14:52
我編輯了我的答案。 – Blackbelt 2012-08-01 11:52:13
工作很完美,謝謝你 – Jasper 2012-08-01 14:43:39