0

我编写了这段代码来尝试保存然后读取一个对象,但是它抛出了一个 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 ......你怎么看?

4

1 回答 1

0

我通过将 os.close 替换为 os.reset();

于 2020-10-27T21:08:11.387 回答