我需要使用这些类来读取一个文件。但是我并不是很明白它们的工作原理。
FileInputStream inFile = new FileInputStream(fileName);
ObjectInputStream inStream = new ObjectInputStream(inFile);
car = (Car)inStream.readObject();
如果car是一个类,究竟在读什么?我对此感到很困惑。
car是类Car的一个实例。
谢谢。
我需要使用这些类来读取一个文件。但是我并不是很明白它们的工作原理。
FileInputStream inFile = new FileInputStream(fileName);
ObjectInputStream inStream = new ObjectInputStream(inFile);
car = (Car)inStream.readObject();
你的代码尝试将已保存到文件流中的对象进行反序列化。
当你的虚拟机关闭时,你的对象实例将会消失。序列化是一种将对象保存到持久性存储(文件、数据库)的方法,因此该对象可以在虚拟机生命周期之外被使用。如果需要再次使用该对象,只需将数据流反序列化为对象即可。
有关序列化的更多信息,请参阅此链接:
http://java.sun.com/developer/technicalArticles/Programming/serialization/
FileInputStream:
FileInputStream 用于打开文件以进行读取。
FileInputStream fis=new FileInputStream("welcome");
它检查文件是否存在,如果文件存在,则打开文件进行读取,否则将抛出FileNotFoundException异常。
ObjectInputStream:
FileInputStream fis=new FileInputStream("welcome");
ObjectInputStream ois=new ObjectInputStream(fis);
它打开文件以读取对象。
FileInputStream
进行加载。如何使用ObjectInputStream
顺序读取它们呢? - Lucas Sousa