如何使用录音机/播放器对象

时间:2012-05-29 10:59:26

标签: java

我正在尝试将对象放入文档中。数据,然后他们可以阅读有谁知道哪里出错了? 我遇到的问题是它能够读取你保存的文件,我不确定你保存它,但如果我在文件夹中找到该文件...

我正在使用像:

这样的objets
public class Person {
    public int Id;
    public String Name;
    public boolean Show;

    public Persona(
            int identificator,
            String newName,
            boolean ShoworNot
            ){
        this.Id = identificator;
        this.Name = newName;
        this.Show = ShoworNot;
    }

Thanks
my code:

public void WriteFile
try {
            FileOutputStream file = new FileOutputStream("try.dat");
            ObjectOutputStream exit = new ObjectOutputStream(file);
            Iterator ite2 = people.iterator();
            while(ite2.hasNext()){
            Person person2 = (Person)ite2.next();
            exit.writeObject(person2);
            exit.close();
        }
            System.out.println("It's works");

        }
        catch (IOException e){
        System.out.println("Problems with the file.");
        }
}
  }
  }
  }
  public void ReadFile(){
      try {
FileInputStream file2 = new FileInputStream("try.dat");
ObjectInputStream entry = new ObjectInputStream(file2);
entry.readObject();
String data = (String)entry.readObject();
        entry.close();
System.out.println(data);
}

catch (FileNotFoundException e) {
System.out.println("It can't open the file document");
}
catch (IOException e) {
System.out.println("Problems with the file");
}
catch (Exception e) {
System.out.println("Error reading the file");
}
}

1 个答案:

答案 0 :(得分:0)

如果要使用Serializable,您的对象必须实现ObjectOutputStream接口。只需将public class Person {更改为public class Person implements Serializable {

即可

另外,要查看问题所在,请在每个块catch{}中写e.printStackTrace()

你有一个错误:

entry.readObject();
String data = (String)entry.readObject();

您正在读取1个对象,忽略它并尝试读取第二个对象,但您已经读过它,因此您处于文件末尾并且您获得了EndOfFileException(EOF)。删除第一行。第二个问题是对象的类型无效。您编写了一个对象Person,因此您必须阅读Person,而不是String

Person data = (Person) entry.readObject();

此外,在您发送文件中的所有数据并关闭流之前,您必须致电.flush()

exit.writeObject(person2);
exit.flush();
exit.close();