-1

ドキュメントにオブジェクトを配置しようとしています。どこが間違っているか知っている人はいますか? 私が抱えている問題は、保持しているファイルを読み取ることができることです。保存したかどうかはわかりませんが、フォルダーにファイルが見つかった場合...

私は次のようなオブジェクトを扱っています:

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");
}
}
4

1 に答える 1

0

Serializableを使用する場合、オブジェクトはインターフェイスを実装する必要がありますObjectOutputStream。に変更public class Person {するだけpublic class Person implements Serializable {

また、問題が何であるかを確認するには、各ブロックでcatch{}書き込みますe.printStackTrace()

間違いがあります:

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

1 つのオブジェクトを読み取り、それを無視して 2 番目のオブジェクトを読み取ろうとしていますが、既に読み取っているため、ファイルの最後にいて EndOfFileException(EOF) が発生します。最初の行を削除します。2 番目の問題は、オブジェクトの型が無効であることです。あなたはオブジェクトを書いているので、以下ではなく、Person読む必要があります:PersonString

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

また、ファイル内のすべてのデータを送信した後、ストリームを閉じる前に呼び出す必要があります.flush()

exit.writeObject(person2);
exit.flush();
exit.close();
于 2012-05-29T11:03:02.007 に答える