0
我試圖將此對象庫存保存到內部存儲。我在課堂上保存和獲取方法。當我嘗試調用保存方法時,最終會出現異常。我有異常信息寫入到logcat的,這裏是我得到的:無法寫入對象。只讀文件系統
2月8日至4日:32:23.690:VERBOSE /亞歷克斯(278):/測試(只讀文件系統)
的文件/測試是「只讀文件系統」,但我已經讓該清單文件中寫入外部存儲:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
這裏的Inventory類。最後兩種方法是保存和讀取方法。
package com.androidbook.inventoryproject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import android.util.Log;
public class Inventory implements Serializable {
private static final long serialVersionUID = 1L;
int numIngred;;
Ingredient[] ingredients;
ArrayList ingred = new ArrayList<Ingredient>();
public Inventory() {
numIngred = 0;
ingredients = new Ingredient[numIngred];
}
public int getNumIngred() {
return numIngred;
}
public String getIngredientName(int n) {
return ((Ingredient)ingred.get(n)).getName();
}
public Ingredient[] getIngredients() {
return ingredients;
}
public Ingredient getIngredient(int n) {
return (Ingredient)ingred.get(n);
}
public void addIngredient(String iname) {
numIngred++;
ingred.add(new Ingredient(iname));
}
public boolean saveInventory(Inventory inv) {
File suspend_f = new File("test");
FileOutputStream fos = null;
ObjectOutputStream oos = null;
boolean keep = true;
try {
fos = new FileOutputStream(suspend_f);
oos = new ObjectOutputStream(fos);
oos.writeObject(inv);
}
catch (Exception e) {
keep = false;
Log.v("alex", "" + e.getMessage());
}
finally {
try {
if (oos != null) oos.close();
if (fos != null) fos.close();
if (keep == false) suspend_f.delete();
}
catch (Exception e) { /* do nothing */ }
}
return keep;
}
public Inventory getInventory() {
File suspend_f = new File("test");
Inventory inven = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try{
fis = new FileInputStream(suspend_f);
ois = new ObjectInputStream(fis);
inven = (Inventory)ois.readObject();
}
catch (Exception e) {
String mess = e.getMessage();
}
finally {
try {
if (fis != null)
fis.close();
if (ois != null)
ois.close();
}
catch (Exception e) { }
}
return inven;
}
}
哦,等等,我其實想寫入文件系統根目錄。我怎麼做?謝謝! –
你不能。基本上只能寫入應用程序的專用存儲區和外部存儲器。 –
@Chris是對的。也許如果你植根於設備並修改了根分區的只讀屬性,你可能會做到這一點,但你永遠無法在未經修改的Android設備上做到這一點。你可能想要做什麼,需要你專門寫入根目錄? – Femi