0

我最近阅读了数千个关于 android 文件序列化的主题,但我仍然没有找到有效的解决方案。

我有我的可序列化类和活动,我分别在其中序列化和反序列ArrayList化可序列化的类元素。 onResume()onPause()

我的解决方案仍然在 seriazlie 和反序列化方法中抛出 IOException 。

package classes;

import java.io.Serializable;
import java.util.Date;

import com.google.android.maps.GeoPoint;

public class Note implements Serializable {

    public Note() {
    }

    public Note(Date date, String name, GeoPoint geoPoint) {
        this.date = date;
        this.name = name;
        this.geoPoint = geoPoint;
    }

    private static final long serialVersionUID = -7789719052842264659L;

    private Date date;
    private String name;
    private GeoPoint geoPoint;

    public Date getDate() {
        return date;
    }

    public String getName() {
        return name;
    }

    public GeoPoint getGeoPoint() {
        return geoPoint;
    }

    @Override
    public String toString() {
        return String.format("Name: %S%nDate: %2$td-%2$tb-%2$tY%nTime: %2$tH:%2$tM:%2$tS", name, date);
    }
}

这是我的方法:

private void serializeQuotes() {
    try {
        FileOutputStream fos = openFileOutput("test.txt", Context.MODE_WORLD_READABLE);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(notes);
        oos.close();
    }
    catch (IOException e) {
        Toast.makeText(this, "Serialization error", Toast.LENGTH_SHORT).show();
    }
}

@SuppressWarnings("unchecked")
private void deserializeQuotes() {
    try {
        FileInputStream fis = openFileInput("test.txt");
        ObjectInputStream ois = new ObjectInputStream(fis);
        notes = (ArrayList<Note>) ois.readObject();
        ois.close();
    }
    catch (IOException e) {
        Toast.makeText(this, "Deserialization error", Toast.LENGTH_SHORT).show();
    }
    catch (ClassNotFoundException e) {
    }
}

notes在哪里

ArrayList<Note>

我需要在 AppFolder 中创建文件:

    File savedLocationsDirectory = new File(Environment.getExternalStorageDirectory().getPath().concat("/AppFolder"));
    if (!savedLocationsDirectory.exists()) savedLocationsDirectory.mkdirs();
    savedLocationsFile = new File(savedLocationsDirectory, "savedLocations.gc");

然后我使用:FileInputStream fis = new FileInputStream(savedLocationsFile);FileOutputStream fos = new FileOutputStream(savedLocationsFile, true);

在这两种情况下,序列化都不起作用。

4

0 回答 0