java中如何读取txt里面的所有对象

fis=newFileInputStream(f);ois=newObjectInputStream(fis);Objectobject=ois.readObject()... fis = new FileInputStream(f);
ois = new ObjectInputStream(fis);
Object object = ois.readObject();这个方法只能读出txt文件里面的第一条数据 而不能得到所有的数据 应该循环去读 但是这个怎么读呢 请教各位大侠
展开
 我来答
李木飞
2012-08-24 · TA获得超过122个赞
知道答主
回答量:81
采纳率:0%
帮助的人:54.9万
展开全部
import java.io.*;
// 在Java中系列化很简单, 只要实现一个无函数的接口Serializable即可。
public class Student implements Serializable {
//private static final long serialVersionUID = -6670528088216041285L;
private String name;
private int ID;
public Student(String name, int ID) {
this.name = name;
this.ID = ID;
}
public String getName() {
return name;
}
public int getID() {
return ID;
}
public static void main(String[] agrs) {
System.getProperties().put("file.encoding","gbk");
// 先产生几个学生的对象
Student st1 = new Student("Google", 100);
Student st2 = new Student("Baidu", 101);
Student st3 = new Student("Yahoo", 102);
// 把对象写入文件.
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("e:\\Test\\data.date"));
oos.writeObject(st1);
oos.writeObject(st2);
oos.writeObject(st3);
st1 = null;
st2 = null;
st3 = null;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
oos = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 把对象从文件读入.
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("e:\\Test\\data.date"));
st3 = (Student) ois.readObject();
st2 = (Student) ois.readObject();
st1 = (Student) ois.readObject();
// 输出从文件中读取到的学生的信息, 用于查检是否正确
System.out.println(st1.getName() + "'s ID is " + st1.getID());
System.out.println(st2.getName() + "'s ID is " + st2.getID());
System.out.println(st3.getName() + "'s ID is " + st3.getID());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (ois != null) {
try {
ois.close();
ois = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
追问
谢谢你   我想用循环的模式取出来,有什么解决方案呢,我怎么才能判断这个文件里面有没有读完呢
百度网友997ab03
2012-08-24 · TA获得超过629个赞
知道小有建树答主
回答量:264
采纳率:0%
帮助的人:351万
展开全部
随便手写的一个,希望对你有帮助。

List<Object> list = new ArrayList<Object>();
Object o = null;
while ((o = ois.readObject()) != null) {
list.add(o);
}
return list;
追问
你好  这样写出了一个java.io.StreamCorruptedException: invalid type code: AC异常    这个怎么解决呢
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式