I have to read in a file using these classes. I don't really understand how they work.
FileInputStream inFile = new FileInputStream(fileName);
ObjectIn开发者_运维问答putStream inStream = new ObjectInputStream(inFile);
car = (Car)inStream.readObject();
If car is a class, what exactly is being read? I'm so confused about this.
car is an instance of the class Car
Thanks
At the most primitive level, you are reading bits in from a file which the FileInputStream is able to do. This is then filtered through the ObjectInputStream which translates these bits into Java objects, but does not know the actual type of the object created, which is why you must cast the object as a Car (hopefully in a try/catch block in case there's an error).
For more on Streams in general, please look here: input Streams
For File input streams, please look here: byte streams
For Object Streams, please look here: Object streams
Your code, try to deserialize the object that been saved to file stream.
Your instance of object will be vanish when your virtual machine down. serialization is a way to save object to a persistence storage (file, database), so the object can be used latter beyond your virtual machine life time. and if you need the object again, just deserialize data stream to object.
for more information about serialization, refer to this link :
http://java.sun.com/developer/technicalArticles/Programming/serialization/
FileInputStream:
FileInputStream is used to open file to read.
FileInputStream fis=new FileInputStream("welcome");
It checks wheither the file exist or not if file exist opens the file for reading otherwise FileNotFoundException will thrown.
ObjectInputStream:
FileInputStream fis=new FileInputStream("welcome");
ObjectInputStream ois=new ObjectInputStream(fis);
It opens the file for reading object.
精彩评论