私はスケジュール帳を作成しており、すべてのオブジェクトを .txt に保存しています。これは正常に動作します。問題はそれらを読み取るときに発生し、プログラムは読み取ります。ファイルの終わりが来ると、プログラムは認識しません。何をすべきか、今は混乱しているので私のコードは入れませんが、これが私の先生のコードです。
try{
//***Instructions for reading***
//It creates a streamobject with the file's name and asigned format
FileInputStream fileIn = new FileInputStream("Serializado.txt");
//It creates an inputobject, so it can represent the object
ObjectInputStream objIn= new ObjectInputStream(fileIn);
while (fileIn != null) {
//with readObject() method, it extracts the object's content
obInp= (NewAlumno) objIn.readObject(); //Se hace un "cast" a NewAlumno
System.out.print("Nombre :" + obInp);
System.out.print(", Sexo: " + obInp.getSexo());
System.out.print(", Direccion: "+ obInp.getDireccion());
System.out.print(", Promedio: " + obInp.getpromedioPoo());
System.out.print(", Telefono: " + obInp.getTelefono()+"\n");
}
objIn.close();
} catch(Exception e){}
}
ご覧のとおり、キャッチ例外は空なので、先生のコードを使用すると問題なく動作しているように見えますが、そこに println を配置すると、常に出力されます。何かが間違っていることを意味し、それが
while(fileIn != null)
なぜなら、Netbeans は、この式が null になることはないと言っているからです。だから私は、プログラムがファイルの終わりに達した後、何をすべきかを知らないと推測しています. よろしくお願いします!
例外は次のとおりです。
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2577)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1315)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
at profegraba.Persistencia.main(Persistencia.java:81)