java使用ObjectInputStream从文件中读取对象,,下面例子演示如何从文件中
分享于 点击 46879 次 点评:288
java使用ObjectInputStream从文件中读取对象,,下面例子演示如何从文件中
下面例子演示如何从文件中读取已经序列化的对象。
我们简单的创建了一个ObjectInputStream对象,然后循环读取其中的对象,知道文件结束抛出EOFException
import java.io.EOFException;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.ObjectInputStream;/** * * @author javadb.com */public class Main { /** *ObjectInputStream 使用示例 */ public void readPersons(String filename) { ObjectInputStream inputStream = null; try { //构造ObjectInputStream对象 inputStream = new ObjectInputStream(new FileInputStream(filename)); Object obj = null; while ((obj = inputStream.readObject()) != null) { if (obj instanceof Person) { System.out.println(((Person)obj).toString()); } } } catch (EOFException ex) { //在读取到文件结束时触发此异常 System.out.println("End of file reached."); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { //Close the ObjectInputStream try { if (inputStream != null) { inputStream.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } /** * @param args the command line arguments */ public static void main(String[] args) { new Main().readPersons("myFile.txt"); }}
用户点评