`
xiang588
  • 浏览: 302627 次
  • 性别: Icon_minigender_1
  • 来自: 甘肃平凉
社区版块
存档分类
最新评论

java中输入输出的总括(初学必看) 5

阅读更多

{
try
{ //添加方式创建文件输出流
FileOutputStream fout = new FileOutputStream(fname,true);
DataOutputStream dout = new DataOutputStream(fout);
dout.writeInt(this.number);
dout.writeChars(this.name+"\n");
dout.close();
}
catch (IOException ioe){}
}
static void display(String fname)
{
try
{
FileInputStream fin = new FileInputStream(fname);
DataInputStream din = new DataInputStream(fin);
int i = din.readInt();
while (i!=-1) //输入流未结束时
{
System.out.print(i+" ");
char ch ;
while ((ch=din.readChar())!='\n') //字符串未结束时
System.out.print(ch);
System.out.println();
i = din.readInt();
}
din.close();
}
catch (IOException ioe){}
}
}
程序运行结果如下:
1 Wang
2 Li
     对象流
•     对象的持续性(Persistence)
–     能够纪录自己的状态一边将来再生的能力,叫对象的持续性
•     对象的串行化(Serialization)
–     对象通过写出描述自己状态的的数值来记录自己的过程叫串行化。串行化的主要任务是写出对象实例变量的数值,如果变量是另一个对象的引用,则引用的对象也要串行化。这个过程是递归的
•     对象流
–     能够输入输出对象的流称为对象流。
–     可以将对象串行化后通过对象输入输出流写入文件或传送到其它地方
在java中,允许可串行化的对象在通过对象流进行传输。只有实现Serializable接口的类才能被串行化, Serializable接口中没有任何方法,当一个类声明实现Serializable接口时,只是表明该类加入对象串行化协议
要串行化一个对象,必须与一定的对象输出/输入流联系起来,通过对象输出流将对象状态保存下来(将对象保存到文件中,或者通过网络传送到其他地方) ,再通过对象输入流将对象状态恢复
类 ObjectOutputStream和ObjectInputStream分别继承了接口ObjectOutput和ObjectInput,将数据流 功能扩展到可以读写对象,前者用writeObject()方法可以直接将对象保存到输出流中,而后者用readObject()方法可以直接从输入流中 读取一个对象
例 8.10 对象流。
本例声明Student2为序列化的类。Save方法中,创建对象输出流out,并以添加方式向文件 中直接写入当前对象out.writeObject(this);display方法中,创建对象输入流in,从文件中直接读取一个对象 in.readObject(),获得该对象的类名、接口名等属性,并显示其中的成员变量。程序如下:
import java.io.*;
public class Student2 implements Serializable //序列化
{
int number=1;
String name;
Student2(int number,String n1)
{
this.number = number;
this.name = n1;
}
Student2()
{
this(0,"");
}
void save(String fname)
{
try
{
FileOutputStream fout = new FileOutputStream(fname);
ObjectOutputStream out = new ObjectOutputStream(fout);
out.writeObject(this); //写入对象
out.close();
}
catch (FileNotFoundException fe){}
catch (IOException ioe){}
}
void display(String fname)
{
try
{
FileInputStream fin = new FileInputStream(fname);
ObjectInputStream in = new ObjectInputStream(fin);
Student2 u1 = (Student2)in.readObject(); //读取对象
System.out.println(u1.getClass().getName()+" "+
u1.getClass().getInterfaces()[0]);
System.out.println(" "+u1.number+" "+u1.name);
in.close();
}
catch (FileNotFoundException fe){}
catch (IOException ioe){}
catch (ClassNotFoundException ioe) {}
}
public static void main(String arg[])
{
String fname = "student2.obj";
Student2 s1 = new Student2(1,"Wang");
s1.save(fname);
s1.display(fname);
}
}
程序运行结果如下:
Student2 interface java.io.Serializable
1 Wang
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics