我想分享我的解決方案,因爲我從這個問題上得到了很多來自Stackoverflow的幫助(通過搜索以前的答案)。我的解決方案導致了幾個小時的搜索和拼湊解決方案。我希望它能幫助別人。
這將向外部存儲器寫入和讀取自定義對象的ArrayList。
我有一個類爲我的活動和其他類提供IO。鬧鐘是我的習慣課。
@SuppressWarnings("unchecked")
public static ArrayList<Alarm> restoreAlarmsFromSDCard(String fileName,
Context context) {
FileInputStream fileInputStream = null;
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();//Alarm is my custom class
//Check if External storage is mounted
if (Environment.getExternalStorageState() != null) {
File dir = new File(Environment.getExternalStorageDirectory(),
"YourAppName/DesiredDirectory");
try {
if (!dir.exists()) {
Log.v("FileIOService", "No Such Directory Exists");
}
File file = new File(dir, fileName);
fileInputStream = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fileInputStream);
alarmList = (ArrayList<Alarm>) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
//Do something here to warn user
}
return alarmList;
}
public static void saveAlarmsToSDCard(String fileName, ArrayList<Alarm> alarmList,Context context) {
FileOutputStream fileOutputStream = null;
ObjectOutputStream objectOutputStream = null;
if (Environment.getExternalStorageState() != null) {
File dir = new File(Environment.getExternalStorageDirectory(),
"YourAppName/DesiredDirectory");
try {
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, fileName);
fileOutputStream = new FileOutputStream(file);
objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(alarmList);
objectOutputStream.close();
} catch (IOException ioException) {
ioException.getMessage();
} catch (Exception e) {
e.getMessage();
}
}else{
//Do something to warn user that operation did not succeed
}
}
您是否已將 添加到您的清單中? –
雅我有它... – Mathew
我有錯誤:java.io.FileNotFoundException:/mnt/sdcard/Cache/mathew/empInfo.ser(是一個目錄)在行fileOutputStream =新的FileOutputStream(文件); – Mathew