2015-03-07 06:30:01
阅读( 1456 )
下面例子演示如何从文件中读取已经序列化的对象。
我们简单的创建了一个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");
}
}
分享给朋友:
亲~ 如果您有更好的答案 可在评论区发表您独到的见解。
您想查看更多的信息:
面试题