Android-保存和读取对象-StreamCorruptedException



我写这段代码是为了尝试保存然后读取对象,但它引发了StreamCorruptedException错误。

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WHClass who = new WHClass();
who.id = 5;
who.distance = 36;
who.name = "Johnny Bravo";

try {
FileOutputStream fos = new FileOutputStream( getStorageDir("run.txt") );
ObjectOutputStream os = new ObjectOutputStream(fos);
os = new ObjectOutputStream(fos);
os.writeObject(who);
os.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"OOOPS WHEN WRITE",Toast.LENGTH_SHORT).show();
}
/////////////////////////////////////////////
try {
FileInputStream fis = new FileInputStream( getStorageDir("run.txt") );
ObjectInputStream is = new ObjectInputStream(fis);
WHClass whoRead = (WHClass) is.readObject();
is.close();
fis.close();
Toast.makeText(getApplicationContext(),whoRead.name,Toast.LENGTH_SHORT).show();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"OOOPS WHEN READ",Toast.LENGTH_SHORT).show();
}


}

类别:

package com.example.xmlreadwriter;
import java.io.Serializable;
public class WHClass implements Serializable {
int id;
int distance;
String name;
}

当我运行它时,保存似乎很好,但读取时出现StreamCorruptedException。。。你觉得怎么样?

我用os.reset((替换了os.close;

最新更新