[英]Android - saving and reading objects - 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 使其工作;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.