【问题标题】:Wrong / nonfunctional serializable错误/非功能可序列化
【发布时间】:2016-07-28 21:21:36
【问题描述】:

您好,我遇到了简单可序列化的问题

这是我的全部课程。没有 getter、setter 和 try & catch

public class myTrip implements Serializable {
String NazovTripu;
int den, mesiac, rok;
String Mesto;
String filename="prve.dat";

public String getFilename() {
    return filename;
}

public void Serializuj(Context context){
    FileOutputStream fos = null;
    fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
    ObjectOutputStream os = new ObjectOutputStream(fos);
    os.writeObject(this);
    os.close();       
}

public myTrip DeSerializuj(Context context) {
    FileInputStream fis = null;       
        fis = context.openFileInput(filename);

    ObjectInputStream is = new ObjectInputStream(fis);
    myTrip mojtrip = (myTrip) is.readObject();
    is.close();
    fis.close();
        return mojtrip;        
    return null;
}

public void DeSerializuj2(Context context) {
    FileInputStream fis = null;

        fis = context.openFileInput(filename);

    ObjectInputStream is = new ObjectInputStream(fis);
    myTrip simpleClass = (myTrip) is.readObject();
    is.close();
    fis.close();

}

我这里有两个变体反序列化但没有工作,我不知道问题出在哪里。如果在序列化或反序列化,请帮助我:)

我在一项活动中使用它

myTrip prvy= new myTrip();
    ...
    prvy.Serializuj(this);

这个代码在 OnCreate 方法的其他活动中

myTrip prvy= new myTrip();
...
prvy.DeSerializuj(this);

应用程序不会崩溃,但变量没有值。

【问题讨论】:

  • 此代码无法编译。贴出真实代码。摆脱DeSerializuj2()。它没有任何用处。它应该返回反序列化的对象,在这种情况下它将与DeSerializuj() 相同。

标签: java android serialization deserialization


【解决方案1】:

这里有很好的序列化和反序列化代码..

 public void Serializuj( myTrip serTrip){
    FileOutputStream fos = null;
    try {
        File file = new File(getApplicationContext().getFilesDir(), "data.dat");
        FileOutputStream fo = new FileOutputStream(file);
        ObjectOutputStream ou = new ObjectOutputStream(fo);
        ou.writeObject(serTrip);
        ou.close();
        fo.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public myTrip DeSerializuj() {
    myTrip   prvy = null;
    try {
        File file = new File(getApplication().getFilesDir(), "data.dat");
        FileInputStream fi = new FileInputStream(file);
        ObjectInputStream oi = new ObjectInputStream(fi);
     prvy = (myTrip) oi.readObject();
        oi.close();
        fi.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return prvy;
}

【讨论】:

    猜你喜欢
    • 2021-10-31
    • 2011-02-08
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多