怎么用JAVA文件流读取文件然后保存到对象中?
1个回答
展开全部
应用public ObjectInputStream(InputStream in)构造一个ObjectionInputStream对象ois,再应用ois的public final Object readObject()读取一个Object对象强制转换为你对象。
ObjectionInputStream ois=new ObjectionInputStream(in);
Object o=ois.readeObject();
ObjectionInputStream ois=new ObjectionInputStream(in);
Object o=ois.readeObject();
追问
您能不能跟我举一个详细的例子?麻烦了!
追答
package com;
import java.io.Serializable;
//注意需要实现Serializable接口,否则无法写入文件中
public class Person implements Serializable{
private static final long serialVersionUID = 1L;
public int id;
public String name;
public Person(){}
}
package com;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Test {
public static void main(String[] args) {
try {
File f=new File("d://temp.txt");
f.createNewFile();
Person p=new Person();
p.id=1;
p.name="test";
FileOutputStream fos=new FileOutputStream(f);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(p);
fos.flush();
fos.close();
FileInputStream fis=new FileInputStream(f);
ObjectInputStream ois=new ObjectInputStream(fis);
Person p1=new Person();
p1=(Person)ois.readObject();
fis.close();
System.out.println("person'id is :"+p1.id+" and person'name is :"+p1.name);
} catch (Exception e) {
e.printStackTrace();
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询