一個簡單的INT []所有我想要做的是保存和更新一個簡單的INT []從一個應用程序20分的高分,我做的,但我不斷收到fileNotFoundExceptions。 我讀:https://developer.android.com/guide/topics/data/data-storage.html#filesExternal,但它並不是特別具體。寫入到Android內存
使用的字段:
private int[] highscores; //initialized as null in onCreate()
private double dynamicHighScore; //calculated from intent that fires activity
代碼:
String fileName = "highscores";
try {
FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis); //firing fileNotFoundException everytime
this.highScores = (int[]) ois.readObject();
Log.d("GameOver", "Object Read");
ois.close();
fis.close();
if (this.highScores.length < 20) {
int[] newHighScores = new int[this.highScores.length + 1];
newHighScores[newHighScores.length - 1] = (int) this.dynamicScore;
this.highScores = newHighScores;
} else if (this.highScores[this.highScores.length - 1] < this.dynamicScore) {
this.highScores[this.highScores.length - 1] = (int) this.dynamicScore;
}
int j;
int key;
int i;
// insertion Sort
for (j = 1; j < highScores.length; j++) {
key = highScores[j];
for (i = j - 1; (i >= 0) && (highScores[i] < key); i--) {
highScores[i + 1] = highScores[i];
}
highScores[i + 1] = key;
}
FileOutputStream fos = openFileOutput(fileName,
Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(highScores);
Log.d("GameOver", "Object rewritten");
oos.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("fnf", "fnf1");
} catch (IOException e) {
e.printStackTrace();
Log.d("IO", "IO1");
} catch (ClassNotFoundException e) {
e.printStackTrace();
Log.d("CNF", "CNF1");
}
if (this.highScores == null) {
try {
this.highScores = new int[] { (int) this.dynamicScore };
FileOutputStream fos = openFileOutput(fileName,
Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(highScores);
Log.d("GameOver", "Object created and written");
oos.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
在GAMEOVER後續運行後,我永遠不能得到的文件被發現0我試圖傳遞一個文件對象,而不是字符串文件名到新的FileInputStream(),但沒有更改 我的Logcat指示對象正在寫入內存,但未從內存中找到。
是否文件路徑必須被更明確地規定, 如果是這樣,在哪裏?
如果文件路徑必須更明確指定,爲什麼我的Logcat日誌成功創建對象並寫入文件?
這個int []是我想保存和訪問內存的唯一對象;任何幫助深表感謝
爲什麼不使用SharePreferences並失去所有的文件邏輯? – Simon