I have written a series of objects to an ObjectOutputStream. I assumed that I could loop on ObjectInputStream.readObject until it returned null, indicating that all objects had been read. However, instead, I get an EOFException after it reads all the objects and attempts to read the next (nonexistent) one. What is the preferred way to detect EOF with Object streams?
I suppose I could write a header that includes the number of objects to follow, but somehow I think there must be a preferred way. Originally posted by Joe Ess: Yes, using exceptions to determine program flow is bad form. In this respect, Object.putStream seems to break the contract that every other stream uses, there being some value to indicate EOF.
If you want to serialize more than one object, package all the objects into a single collection (i.e. An list or map) and serialize the collection. Then you don't have to catch the EOF and get all your data in one simple readObject call. So you must be certain that the implementation of that collection you use don't change in a futur jdk version, because else you can't read your file.
Joe: Yes, using exceptions to determine program flow is bad form. In this respect, Object.putStream seems to break the contract that every other stream uses, there being some value to indicate EOF.
It would've made sense if they'd simply returned null in this case - at least, it would've ben consisten with other streams. But they didn't; too bad. Wrapping the objects in a Collection or array is one way to handle this problem. Another is to use writeInt to write the number of serialized objects that will be in the stream, before you write the objects themselves. The the reading stream needs to first readInt to get the number of objects, then readObject that many times.
Another solution is to use a variant of the - create an object which indicates the end of the stream. This is particularly useful if you don't know how many objects there will be before you start to write them. Sudha: I suppose you can try using the available method. Please, don't. The problem with available is that is often does what people want, but sometimes does something different. Which means that when something does go wrong, it's difficult to replicate it reliably, and therefore very difficult to track down. The problem is that available does not necessarily have anything to do with EOF or stream closure.
The number returned by available only tells you how many bytes are available right now, without blocking. Maybe no more bytes are available because a file is fragmented and it takes a few more milliseconds for the disk reader to move to the next fragment. Or maybe there is a hardware buffer somewhere in the system which is smaller than the requested number of bytes, and the system is designed to return the size of the available buffer (which will then be reloaded shortly after it's been read).
Or maybe (very often, in fact) you're reading across some sort of network connection and the remaining bytes simply have not been sent yet from the other side of the connection. In all these cases, available does not tell you actual number of bytes remaining to be read.
The method is massively useless, except for a few cases where it was mildly useful for some pitiful attempts at nonblocking IO prior to JDK 1.4. Ever since JDK 1.4 though, the java.nio package offers better alternatives for that sort of thing. There is really no good reason to use available nowadays.
Roel: so you must be certain that the implementation of that collection you use don't change in a futur jdk version, because else you can't read your file. Yes, but that's true whenever you use serialization. In practice, standard collections such as ArrayList and HashMap are protected against this. They've defined serialVersionUID (from when they were first defined), and Sun is unlikely to change them enough to make them incompatible with previous versions. In comparison, it's much more likely that the class of the objects within the collection will change over time. And that's an issue whether you wrap the objects in a collection or not. October 21, 2005: Message edited by: Jim Yingst.
You're precise, they are suspects, and that i don't see Robert Murat annoying get entry to to their archives. In the event that they are harmless, then they be attentive to that there won't have the capacity to be something incriminating in the archives, so as a result they don't might desire to ascertain them because of the fact their legal experts can effectively sparkling them. If there is no information, there could be no rates. Won't have the capacity to they save themselves out of the papers for at some point? Enable the police do their activity, and quit with the statements from Clarence (the worst spokesman in the international.). Tell us some more.
Upload in Progress. Upload failed. Please upload a file larger than 100x100 pixels. We are experiencing some problems, please try again. You can only upload files of type PNG, JPG, or JPEG. You can only upload files of type 3GP, 3GPP, MP4, MOV, AVI, MPG, MPEG, or RM. You can only upload photos smaller than 5 MB.
You can only upload videos smaller than 600MB. You can only upload a photo (png, jpg, jpeg) or a video (3gp, 3gpp, mp4, mov, avi, mpg, mpeg, rm). You can only upload a photo or a video.
Video should be smaller than 600mb/5 minutes. Photo should be smaller than 5mb.
An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream. ObjectOutputStream and ObjectInputStream can provide an application with persistent storage for graphs of objects when used with a FileOutputStream and FileInputStream respectively.
ObjectInputStream is used to recover those objects previously serialized. Other uses include passing objects between hosts using a socket stream or for marshaling and unmarshaling arguments and parameters in a remote communication system. ObjectInputStream ensures that the types of all objects in the graph created from the stream match the classes present in the Java Virtual Machine. Classes are loaded as required using the standard mechanisms. Only objects that support the java.io.Serializable or java.io.Externalizable interface can be read from streams.
The method readObject is used to read an object from the stream. Java's safe casting should be used to get the desired type. In Java, strings and arrays are objects and are treated as objects during serialization.
When read they need to be cast to the expected type. Primitive data types can be read from the stream using the appropriate method on DataInput. The default deserialization mechanism for objects restores the contents of each field to the value and type it had when it was written.
Fields declared as transient or static are ignored by the deserialization process. References to other objects cause those objects to be read from the stream as necessary. Graphs of objects are restored correctly using a reference sharing mechanism. New objects are always allocated when deserializing, which prevents existing objects from being overwritten.
Reading an object is analogous to running the constructors of a new object. Memory is allocated for the object and initialized to zero (NULL). No-arg constructors are invoked for the non-serializable classes and then the fields of the serializable classes are restored from the stream starting with the serializable class closest to java.lang.object and finishing with the object's most specific class. For example to read from a stream as written by the example in ObjectOutputStream: FileInputStream fis = new FileInputStream('t.tmp'); ObjectInputStream ois = new ObjectInputStream(fis); int i = ois.readInt; String today = (String) ois.readObject; Date date = (Date) ois.readObject; ois.close; Classes control how they are serialized by implementing either the java.io.Serializable or java.io.Externalizable interfaces. Implementing the Serializable interface allows object serialization to save and restore the entire state of the object and it allows classes to evolve between the time the stream is written and the time it is read.
It automatically traverses references between objects, saving and restoring entire graphs. Serializable classes that require special handling during the serialization and deserialization process should implement the following methods: private void writeObject(java.io.ObjectOutputStream stream) throws IOException; private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException; private void readObjectNoData throws ObjectStreamException; The readObject method is responsible for reading and restoring the state of the object for its particular class using data written to the stream by the corresponding writeObject method. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is restored by reading data from the ObjectInputStream for the individual fields and making assignments to the appropriate fields of the object. Reading primitive data types is supported by DataInput. Any attempt to read object data which exceeds the boundaries of the custom data written by the corresponding writeObject method will cause an OptionalDataException to be thrown with an eof field value of true. Non-object reads which exceed the end of the allotted data will reflect the end of data in the same way that they would indicate the end of the stream: bytewise reads will return -1 as the byte read or number of bytes read, and primitive reads will throw EOFExceptions.
If there is no corresponding writeObject method, then the end of default serialized data marks the end of the allotted data. Primitive and object read calls issued from within a readExternal method behave in the same manner-if the stream is already positioned at the end of data written by the corresponding writeExternal method, object reads will throw OptionalDataExceptions with eof set to true, bytewise reads will return -1, and primitive reads will throw EOFExceptions. Note that this behavior does not hold for streams written with the old ObjectStreamConstants.PROTOCOLVERSION1 protocol, in which the end of data written by writeExternal methods is not demarcated, and hence cannot be detected. Minecraft block textures 16 by 16. The readObjectNoData method is responsible for initializing the state of the object for its particular class in the event that the serialization stream does not list the given class as a superclass of the object being deserialized. This may occur in cases where the receiving party uses a different version of the deserialized instance's class than the sending party, and the receiver's version extends classes that are not extended by the sender's version. This may also occur if the serialization stream has been tampered; hence, readObjectNoData is useful for initializing deserialized objects properly despite a 'hostile' or incomplete source stream.
Serialization does not read or assign values to the fields of any object that does not implement the java.io.Serializable interface. Subclasses of Objects that are not serializable can be serializable.
In this case the non-serializable class must have a no-arg constructor to allow its fields to be initialized. In this case it is the responsibility of the subclass to save and restore the state of the non-serializable class. It is frequently the case that the fields of that class are accessible (public, package, or protected) or that there are get and set methods that can be used to restore the state. Any exception that occurs while deserializing an object will be caught by the ObjectInputStream and abort the reading process. Implementing the Externalizable interface allows the object to assume complete control over the contents and format of the object's serialized form.
The methods of the Externalizable interface, writeExternal and readExternal, are called to save and restore the objects state. When implemented by a class they can write and read their own state using all of the methods of ObjectOutput and ObjectInput. It is the responsibility of the objects to handle any versioning that occurs. Enum constants are deserialized differently than ordinary serializable or externalizable objects.
The serialized form of an enum constant consists solely of its name; field values of the constant are not transmitted. To deserialize an enum constant, ObjectInputStream reads the constant name from the stream; the deserialized constant is then obtained by calling the static method Enum.valueOf(Class, String) with the enum constant's base type and the received constant name as arguments. Like other serializable or externalizable objects, enum constants can function as the targets of back references appearing subsequently in the serialization stream.
The process by which enum constants are deserialized cannot be customized: any class-specific readObject, readObjectNoData, and readResolve methods defined by enum types are ignored during deserialization. Similarly, any serialPersistentFields or serialVersionUID field declarations are also ignored-all enum types have a fixed serialVersionUID of 0L.
@EJP's answer has nailed it. However if you are a paid-up member of the 'exceptions should't be used for normal flow control' club.
then you can avoid having to catch the exception if you can use some other means to determine when to stop; for example. You could start the stream with a count sent as an int or an Integer object. You could mark the end the stream by sending a null. You could mark the end the stream by sending a special object that means 'this is the end'. It does not need to be a MyClass instance.
Input Past End Of File
You could send a List. Though that means that you can't 'stream' the objects.
Vi Delete To End Of File
Note that this implies that you are able to change the sender-side code. Membership of this club requires either the ability to assimilate circular arguments, or willingness to blindly accept dogma as truth.:-) Rather than repeat the arguments ad nauseam, here are some links to some of my answers related to the 'normal flow control' debate:. If you read through them, you will see that I don't come down firmly on either side of the fence. Rather, my view is that you should understand the trade-offs, and make a decision about whether exceptions are appropriate or not on a case-by-case basis.
You're precise, they are suspects, and that i don't see Robert Murat annoying get entry to to their archives. In the event that they are harmless, then they be attentive to that there won't have the capacity to be something incriminating in the archives, so as a result they don't might desire to ascertain them because of the fact their legal experts can effectively sparkling them. If there is no information, there could be no rates. Won't have the capacity to they save themselves out of the papers for at some point?
Enable the police do their activity, and quit with the statements from Clarence (the worst spokesman in the international.). Tell us some more. Upload in Progress. Upload failed. Please upload a file larger than 100x100 pixels. We are experiencing some problems, please try again. You can only upload files of type PNG, JPG, or JPEG.
Reached End Of File While Parsing
You can only upload files of type 3GP, 3GPP, MP4, MOV, AVI, MPG, MPEG, or RM. You can only upload photos smaller than 5 MB.
You can only upload videos smaller than 600MB. You can only upload a photo (png, jpg, jpeg) or a video (3gp, 3gpp, mp4, mov, avi, mpg, mpeg, rm). You can only upload a photo or a video. Video should be smaller than 600mb/5 minutes. Photo should be smaller than 5mb.