服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

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

 第八章 输入输出流
【课前思考】
1.     字节流和字符流的基类各是什么?
2.     什么是对象的串行化?对象串行化的作用是什么?
【学习目标】
本讲主要讲述了java语言中的输入/输出的处理,通过本讲的学习,同学们可以编写更为完善的java程序。
【学习指南】
仔细阅读本章各知识点的内容, 深刻理解 java 语言中输入/输出流的处理方法,掌握处理问题的方法,多练习,多上机。
【难 重 点】
     遇到实际问题时,要根据需要正确使用各种输入/输出流,特别是对中文使用适当的字符输入流。
     正确使用对象串行化的方法。
     处理字符流时,其构造方法的参数是一个字节流。
     对象串行化的概念。
【知 识 点】
     i/o 流概述
     文件处理
     过滤流
     字符流的处理
     对象的串行化
     其它常用的流
【内 容】
第一节 数据流的基本概念
     理解数据流
流一般分为输入流(input stream)和输出流(output stream)两类,但这种划分并不是绝对的。比如一个文件,当向其中写数据时,它就是一个输出流;当从其中读取数据时,它就是一个输入流。当然,键盘只是一个数人流,而屏幕则只是一个输出流。
     java的标准数据流
标准输入输出指在字符方式下(如dos),程序与系统进行交互的方式,分为三种:
标准输入studin,对象是键盘。
标准输出stdout,对象是屏幕。
标准错误输出stderr,对象也是屏幕。
例 8.1 从键盘输入字符。
本例用system.in.read(buffer)从键盘输入一行字符,存储在缓冲区buffer中,count保存实际读入的字节个数,再以整数和字符两种方式输出buffer中的值。read方法在java.io包中,而且要抛出ioexception异常。程序如下:
import java.io.*;
public class input1
{
public static void main(string args[]) throws ioexception
{
system.out.println("input: ");
byte buffer[] = new byte[512]; //输入缓冲区
int count = system.in.read(buffer); //读取标准输入流
system.out.println("output: ");
for (int i=0;i<count;i++) 输出buffer元素值
{
system.out.print(" "+buffer[i]);
}
system.out.println();
for (int i=0;i<count;i++) 按字符方式输出buffer
{
system.out.print((char) buffer[i]);
}
system.out.println("count = "+ count); //buffer实际长度
}
}
程序中,main方法采用throws子句抛出ioexception异常交由系统处理。
     java.io包中的数据流及文件类
字节流:
  从inputstream和outputstream派生出来的一系列类。这类流以字节(byte)为基本处理单位。
     inputstream、outputstream
     ◇ fileinputstream、fileoutputstream
     ◇ pipedinputstream、pipedoutputstream
     ◇ bytearrayinputstream、bytearrayoutputstream
     ◇ filterinputstream、filteroutputstream
     ◇ datainputstream、dataoutputstream
     ◇ bufferedinputstream、bufferedoutputstream
字符流:
  从reader和writer派生出的一系列类,这类流以16位的unicode码表示的字符为基本处理单位
     reader、writer
     ◇ inputstreamreader、outputstreamwriter
     ◇ filereader、filewriter
     ◇ chararrayreader、chararraywriter
     ◇ pipedreader、pipedwriter
     ◇ filterreader、filterwriter
     ◇ bufferedreader、bufferedwriter
     ◇ stringreader、stringwriter



第二节 字节流初步
inputstream 和outputstream
     read():从流中读入数据
     skip():跳过流中若干字节数
     available():返回流中可用字节数
     mark():在流中标记一个位置
     reset():返回标记过得位置
     marksupport():是否支持标记和复位操作
     close():关闭流
     int read()
从输入流中读一个字节,形成一个0~255之间的整数返回(是一个抽象方法)。
     int read(byte b[])
读多个字节到数组中。
     int read(byte b[], int off, int len)
     write(int b)
将一个整数输出到流中(只输出低位字节,抽象)
     write(byte b[])
将字节数组中的数据输出到流中
     write(byte b[], int off, int len)
将数组b中从off指定的位置开始,长度为len的数据输出到流中
     flush():刷空输出流,并将缓冲区中的数据强制送出
     close():关闭流
从输入流中读取长度为len的数据,写入数组b中从索引off开始的位置,并返回读取得字节数。
进行i/o操作时可能会产生i/o例外,属于非运行时例外,应该在程序中处理。如:型filenotfoundexception, eofexception, ioexception
例 8.2 打开文件。
本例以fileinputstream的read(buffer)方法,每次从源程序文件openfile.java中读取512个字节,存储在缓冲区buffer中,再将以buffer中的值构造的字符串new string(buffer)显示在屏幕上。程序如下:
import java.io.*;
public class openfile
{
public static void main(string args[]) throws ioexception
{
try
{ //创建文件输入流对象
fileinputstream rf = new fileinputstream("openfile.java");
int n=512;
byte buffer[] = new byte[n];
while ((rf.read(buffer,0,n)!=-1) && (n>0)) //读取输入流
{
system.out.print(new string(buffer));
}
system.out.println();
rf.close(); //关闭输入流
}
catch (ioexception ioe)
{
system.out.println(ioe);
}
catch (exception e)
{
system.out.println(e);
}
}
}
例 8.3 写入文件。
本例用system.in.read(buffer)从键盘输入一行字符,存储在缓冲区buffer中,再以fileoutstream的write(buffer)方法,将buffer中内容写入文件write1.txt中,程序如下:
import java.io.*;
public class write1
{
public static void main(string args[])
{
try
{
system.out.print("input: ");
int count,n=512;
byte buffer[] = new byte[n];
count = system.in.read(buffer); //读取标准输入流
fileoutputstream wf = new fileoutputstream("write1.txt");
//创建文件输出流对象
wf.write(buffer,0,count); //写入输出流
wf.close(); //关闭输出流
system.out.println("save to write1.txt!");
}
catch (ioexception ioe)
{
system.out.println(ioe);
}
catch (exception e)
{
system.out.println(e);
}
}
}



第三节 文件操作
     file类
file类声明如下:
public class file ectends object implements serializable,comparable
构造方法:
public file(string pathname)
public file(file patent,string chile)
public file(string patent,string child)
文件名的处理
     string getname( ); //得到一个文件的名称(不包括路径)
     string getpath( ); //得到一个文件的路径名
     string getabsolutepath( );//得到一个文件的绝对路径名
     string getparent( ); //得到一个文件的上一级目录名
     string renameto(file newname); //将当前文件名更名为给定文件的完整路径
文件属性测试
     boolean exists( ); //测试当前file对象所指示的文件是否存在
     boolean canwrite( );//测试当前文件是否可写
     boolean canread( );//测试当前文件是否可读
     boolean isfile( ); //测试当前文件是否是文件(不是目录)
     boolean isdirectory( ); //测试当前文件是否是目录
普通文件信息和工具
     long lastmodified( );//得到文件最近一次修改的时间
     long length( ); //得到文件的长度,以字节为单位
     boolean delete( ); //删除当前文件
目录操作
     boolean mkdir( ); //根据当前对象生成一个由该对象指定的路径
     string list( ); //列出当前目录下的文件
例 8.4 自动更新文件。
本例使用file类对象对指定文件进行自动更新的操作。程序如下:
import java.io.*;
import java.util.date;
import java.text.simpledateformat;
public class updatefile
{
public static void main(string args[]) throws ioexception
{
string fname = "write1.txt"; //待复制的文件名
string childdir = "backup"; //子目录名
new updatefile().update(fname,childdir);
}
public void update(string fname,string childdir) throws ioexception
{
file f1,f2,child;
f1 = new file(fname); //当前目录中创建文件对象f1
child = new file(childdir); //当前目录中创建文件对象child
if (f1.exists())
{
if (!child.exists()) //child不存在时创建子目录
child.mkdir();
f2 = new file(child,fname); //在子目录child中创建文件f2
if (!f2.exists() || //f2不存在时或存在但日期较早时
f2.exists()&&(f1.lastmodified() > f2.lastmodified()))
copy(f1,f2); //复制
getinfo(f1);
getinfo(child);
}
else
system.out.println(f1.getname()+" file not found!");
}
public void copy(file f1,file f2) throws ioexception
{ //创建文件输入流对象
fileinputstream rf = new fileinputstream(f1);
fileoutputstream wf = new fileoutputstream(f2);
//创建文件输出流对象
int count,n=512;
byte buffer[] = new byte[n];
count = rf.read(buffer,0,n); //读取输入流
while (count != -1)
{
wf.write(buffer,0,count); //写入输出流
count = rf.read(buffer,0,n);
}
system.out.println("copyfile "+f2.getname()+" !");
rf.close(); //关闭输入流
wf.close(); //关闭输出流
}
public static void getinfo(file f1) throws ioexception
{
simpledateformat sdf;
sdf= new simpledateformat("yyyy年mm月dd日hh时mm分");
if (f1.isfile())
system.out.println("<file>/t"+f1.getabsolutepath()+"/t"+
f1.length()+"/t"+sdf.format(new date(f1.lastmodified())));
else
{
system.out.println("

/t"+f1.getabsolutepath());
file[] files = f1.listfiles();
for (int i=0;i<files.length;i++)
getinfo(files[i]);
}
}
}
f1.lastmodified()返回一个表示日期的长整型,值为从1970年1月1日零时开始计算的毫秒数,并以此长整型构造一个日期对象,再按指定格式输出日期。程序运行结果如下:<file>     d:/myjava/write1.txt          6     2002年12月11日02时18分      d:/myjava/backup<file>     d:/myjava/backup/write1.txt     6     2002年12月31日05时13分
     文件过滤器
类filterinputstream和filteroutputstream分别对其他输入/输出流进行特殊处理,它们在读/写数据的同时可以对数据进行特殊处理。另外还提供了同步机制,使得某一时刻只有一个线程可以访问一个输入/输出流
类filterinputstream和filteroutputstream分别重写了父类inputstream和outputstream的所有方法,同时,它们的子类也应该重写它们的方法以满足特定的需要
•     要使用过滤流,首先必须把它连接到某个输入/输出流上,通常在构造方法的参数中指定所要连接的流:
?c     filterinputstream(inputstream in);
?c     filteroutputstream(outputstream out);
这两个类是抽象类,构造方法也是保护方法
类bufferedinputstream和bufferedoutputstream实现了带缓冲的过滤流,它提供了缓冲机制,把任意的i/o流“捆绑”到缓冲流上,可以提高读写效率
•     在初始化时,除了要指定所连接的i/o流之外,还可以指定缓冲区的大小。缺省大小的缓冲区适合于通常的情形;最优的缓冲区大小常依赖于主机操作系统、可使用的内存空间以及机器的配置等;一般缓冲区的大小为内存页或磁盘块等地整数倍,如8912字节或更小。
?c     bufferedinputstream(inputstream in[, int size])
?c     bufferedoutputstream(outputstream out[, int size])
例 8.5 列出当前目录中带过滤器的文件名清单。
本例实现filenamefilter接口中的accept方法,在当前目录中列出带过滤器的文件名。
程序如下:
import java.io.*;
public class dirfilter implements filenamefilter
{
private string prefix="",suffix=""; //文件名的前缀、后缀
public dirfilter(string filterstr)
{
filterstr = filterstr.tolowercase();
int i = filterstr.indexof('*');
int j = filterstr.indexof('.');
if (i>0)
prefix = filterstr.substring(0,i);
if (j>0)
suffix = filterstr.substring(j+1);
}
public static void main(string args[])
{ //创建带通配符的文件名过滤器对象
filenamefilter filter = new dirfilter("w*abc.txt");
file f1 = new file("");
file curdir = new file(f1.getabsolutepath(),""); //当前目录
system.out.println(curdir.getabsolutepath());
string[] str = curdir.list(filter); //列出带过滤器的文件名清单
for (int i=0;i<str.length;i++)
system.out.println("/t"+str[i]);
}
public boolean accept(file dir, string filename)
{
boolean yes = true;
try
{
filename = filename.tolowercase();
yes = (filename.startswith(prefix)) &
(filename.endswith(suffix));
}
catch(nullpointerexception e)
{
}
return yes;
}
}
程序运行时,列出当前目录中符合过滤条件“w*.txt“的文件名清单。结果如下:
d:/myjava
     write1.txt
     write2.txt
     文件对话框
     随机文件操作
于inputstream 和outputstream 来说,它们的实例都是顺序访问流,也就是说,只能对文件进行顺序地读/写。随机访问文件则允许对文件内容进行随机读/写。在java中,类randomaccessfile 提供了随机访问文件的方法。类randomaccessfile的声明为:
public class randomaccessfile extends object implements datainput, dataoutput
     file:以文件路径名的形式代表一个文件
     filedescriptor:代表一个打开文件的文件描述
     filefilter & filenamefilter:用于列出满足条件的文件
     file.list(filenamefilter fnf)
     file.listfiles(filefilter ff)
     filedialog.setfilenamefilter(filenamefilter fnf)
•     fileinputstream & filereader:顺序读文件
•     fileoutputstream & filewriter:顺序写文件
•     randomaccessfile:提供对文件的随机访问支持
类randomaccessfile则允许对文件内容同时完成读和写操作,它直接继承object,并且同时实现了接口datainput和dataoutput,提供了支持随机文件操作的方法
     datainput和dataoutput中的方法
•     readint(), writedouble()…
     int skipbytes(int n):将指针乡下移动若干字节
     length():返回文件长度
     long getfilepointer():返回指针当前位置
     void seek(long pos):将指针调到所需位置
     void setlength(long newlength):设定文件长度
构造方法:
randomaccessfile(file file, string mode)
     randomaccessfile(string name, string mode)
mode 的取值
?c     “r” 只读. 任何写操作都将抛出ioexception。
?c     “rw” 读写. 文件不存在时会创建该文件,文件存在时,原文件内容不变,通过写操作改变文件内容。
?c     “rws” 同步读写. 等同于读写,但是任何协操作的内容都被直接写入物理文件,包括文件内容和文件属性。
?c     “rwd” 数据同步读写. 等同于读写,但任何内容写操作都直接写到物理文件,对文件属性内容的修改不是这样。
例 8.6 随机文件操作。
本例对一个二进制整数文件实现访问操作当以可读写方式“rw“打开一个文件”prinmes.bin“时,如果文件不存在,将创建一个新文件。先将2作为最小素数写入文件,再依次测试100以内的奇数,将每次产生一个素数写入文件尾。
程序如下:
import java.io.*;
public class primesfile
{
randomaccessfile raf;
public static void main(string args[]) throws ioexception
{
(new primesfile()). createprime(100);
}
public void createprime(int max) throws ioexception
{
raf=new randomaccessfile("primes.bin","rw");//创建文件对象
raf.seek(0); //文件指针为0
raf.writeint(2); //写入整型
int k=3;
while (k<=max)
{
if (isprime(k))
raf.writeint(k);
k = k+2;
}
output(max);
raf.close(); //关闭文件
}
public boolean isprime(int k) throws ioexception
{
int i=0,j;
boolean yes = true;
try
{
raf.seek(0);
int count = (int)(raf.length()/4); //返回文件字节长度
while ((i<=count) && yes)
{
if (k % raf.readint()==0) //读取整型
yes = false;
else
i++;
raf.seek(i*4); //移动文件指针
}
} catch(eofexception e) { } //捕获到达文件尾异常
return yes;
}
public void output(int max) throws ioexception
{
try
{
raf.seek(0);
system.out.println("[2.."+max+"]中有 "+
(raf.length()/4)+" 个素数:");
for (int i=0;i<(int)(raf.length()/4);i++)
{
raf.seek(i*4);
system.out.print(raf.readint()+" ");
if ((i+1)%10==0) system.out.println();
}
} catch(eofexception e) { }
system.out.println();
}
}
程序运行时创建文件“primes.bin“,并将素数写入其中,结果如下:
[2..100]中有 25 个素数:
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97



第四节 字符流
reader类和writer类
前面说过,在jdk1.1之前,java.io包中的流只有普通的字节流(以byte为基本处理单位的流),这种流对于以16位的unicode码表示的字符流处理很不方便。从jdk1.1开始, java.io包中加入了专门用于字符流处理的类,它们是以reader和writer为基础派生的一系列类
同类inputstream和outputstream一样,reader和writer也是抽象类,只提供了一系列用于字符流处理的接口。它们的方法与类inputstream和outputstream类似,只不过其中的参数换成字符或字符数组
reader类
•     void close()
•     void mark(int readaheadlimit)
•     boolean marksupported() :
•     int read()
•     int read(char[] cbuf)
•     int read(char[] cbuf, int off, int len)
•     boolean ready()
•     void reset()
•     long skip(long n)
writer类
•     void close()
•     void flush()
•     void write(char[] cbuf)
•     void write(char[] cbuf, int off, int len)
•     void write(int c)
•     void write(string str)
•     void write(string str, int off, int len)
例 8.7 文件编辑器。
本例实现文件编辑器中的打开、保存文件功能。程序如下:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class editfile1 extends windowadapter
implements actionlistener,textlistener
{
frame f;
textarea ta1;
panel p1;
textfield tf1;
button b1,b2,b3;
filedialog fd;
file file1 = null;
public static void main(string args[])
{
(new editfile1()).display();
}
public void display()
{
f = new frame("editfile");
f.setsize(680,400);
f.setlocation(200,140);
f.setbackground(color.lightgray);
f.addwindowlistener(this);
tf1 = new textfield();
tf1.setenabled(false);
tf1.setfont(new font("dialog",0,20)); //设置文本行的初始字体
f.add(tf1,"north");
ta1 = new textarea();
ta1.setfont(new font("dialog",0,20)); //设置文本区的初始字体
f.add(ta1);
ta1.addtextlistener(this); //注册文本区的事件监听程序
p1 = new panel();
p1.setlayout(new flowlayout(flowlayout.left));
b1 = new button("open");
b2 = new button("save");
b3 = new button("save as");
p1.add(b1);
p1.add(b2);
p1.add(b3);
b2.setenabled(false);
b3.setenabled(false);
b1.addactionlistener(this); //注册按钮的事件监听程序
b2.addactionlistener(this);
b3.addactionlistener(this);
f.add(p1,"south");
f.setvisible(true);
}
public void textvaluechanged(textevent e)
{ //实现textlistener接口中的方法,对文本区操作时触发
b2.setenabled(true);
b3.setenabled(true);
}
public void actionperformed(actionevent e)
{
if (e.getsource()==b1) //单击[打开]按钮时
{
fd = new filedialog(f,"open",filedialog.load);
fd.setvisible(true); //创建并显示打开文件对话框
if ((fd.getdirectory()!=null) && (fd.getfile()!=null))
{
tf1.settext(fd.getdirectory()+fd.getfile());
try //以缓冲区方式读取文件内容
{
file1 = new file(fd.getdirectory(),fd.getfile());
filereader fr = new filereader(file1);
bufferedreader br = new bufferedreader(fr);
string aline;
while ((aline=br.readline()) != null)//按行读取文本
ta1.append(aline+"/r/n");
fr.close();
br.close();
}
catch (ioexception ioe)
{
system.out.println(ioe);
}
}
}
if ((e.getsource()==b2) || (e.getsource()==b3))
{ //单击[保存]按钮时
if ((e.getsource()==b3) ||(e.getsource()==b2)&&(file1==null))
{ //单击[saveas]按钮时,或单击[save]按钮且文件对象为空时
fd = new filedialog(f,"save",filedialog.save);
if (file1==null)
fd.setfile("edit1.txt");
else
fd.setfile(file1.getname());
fd.setvisible(true); //创建并显示保存文件对话框

if ((fd.getdirectory()!=null) && (fd.getfile()!=null))
{
tf1.settext(fd.getdirectory()+fd.getfile());
file1 = new file(fd.getdirectory(),fd.getfile());
save(file1);
}
}
else
save(file1);
}
}
public void save(file file1)
{
try //将文本区内容写入字符输出流
{
filewriter fw = new filewriter(file1);
fw.write(ta1.gettext());
fw.close();
b2.setenabled(false);
b3.setenabled(false);
}
catch (ioexception ioe)
{
system.out.println(ioe);
}
}
public void windowclosing(windowevent e)
{
system.exit(0);
}
}



第五节 字节流的高级应用
     管道流
管道用来把一个程序、线程和代码块的输出连接到另一个程序、线程和代码块的输入。java.io中提供了类pipedinputstream和pipedoutputstream作为管道的输入/输出流
管道输入流作为一个通信管道的接收端,管道输出流则作为发送端。管道流必须是输入输出并用,即在使用管道前,两者必须进行连接
管道输入/输出流可以用两种方式进行连接:
?c     在构造方法中进行连接
•     pipedinputstream(pipedoutputstream pos);
•     pipedoutputstream(pipedinputstream pis);
?c     通过各自的connect()方法连接
•     在类pipedinputstream中,connect(pipedoutputstream pos);
     
•     在类pipedoutputstream中,connect(pipedinputstream pis);
例 8.8 管道流。
本例例管道流的使用方法。设输入管道in与输出管道out已连接,send线程向输出管道out发送数据,receive线程从输入管道in中接收数据。程序如下:
import java.io.*;
public class pipedstream
{
public static void main (string args[])
{
pipedinputstream in = new pipedinputstream();
pipedoutputstream out = new pipedoutputstream();
try
{
in.connect(out);
}
catch(ioexception ioe) { }
send s1 = new send(out,1);
send s2 = new send(out,2);
receive r1 = new receive(in);
receive r2 = new receive(in);
s1.start();
s2.start();
r1.start();
r2.start();
}
}
class send extends thread //发送线程
{
pipedoutputstream out;
static int count=0; //记录线程个数
int k=0;
public send(pipedoutputstream out,int k)
{
this.out= out;
this.k= k;
this.count++; //线程个数加1
}
public void run( )
{
system.out.print("/r/nsend"+this.k+": "+this.getname()+" ");
int i=k;
try
{
while (i<10)
{
out.write(i);
i+=2;
sleep(1);
}
if (send.count==1) //只剩一个线程时
{
out.close(); //关闭输入管道流
system.out.println(" out closed!");
}
else
this.count--; //线程个数减1
}
catch(interruptedexception e) { }
catch(ioexception e) { }
}
}
class receive extends thread //接收线程
{
pipedinputstream in;
public receive(pipedinputstream in)
{
this.in = in;
}
public void run( )
{
system.out.print("/r/nreceive: "+this.getname()+" ");
try
{
int i = in.read();
while (i!=-1) //输入流未结束时
{
system.out.print(i+" ");
i = in.read();
sleep(1);
}
in.close(); //关闭输入管道流
}
catch(interruptedexception e) { }
catch(ioexception e)
{
system.out.println(e);
}
}
}
程序运行结果如下:
send1: thread-0
send2: thread-1
receive: thread-2 1
receive: thread-3 2 3 4 5 7 out closed!
6 8 9 java.io.ioexception: pipe closed!
     数据流
datainputstream和dataoutputstream
     在提供了字节流的读写手段的同时,
     以统一的通用的形式向输入流中写入boolean,int,long,double等基本数据类型,并可以在次把基本数据类型的值读取回来。
     提供了字符串读写的手段。
     分别实现了datainput和dataoutput接口
声明类:
public class datainputstream extends filterinputstream implements datainput
例 8.9 数据流。
本例演示数据流的使用方法。
程序如下:
import java.io.*;
public class datastream
{
public static void main(string arg[])
{
string fname = "student1.dat";
new student1("wang").save(fname);
new student1("li").save(fname);
student1.display(fname);
}
}
class student1
{
static int count=0;
int number=1;
string name;
student1(string n1)
{
this.count++; //编号自动加1
this.number = this.count;
this.name = n1;
}
student1()
{
this("");
}
void save(string fname)
{
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)
?c     能够纪录自己的状态一边将来再生的能力,叫对象的持续性
•     对象的串行化(serialization)
?c     对象通过写出描述自己状态的的数值来记录自己的过程叫串行化。串行化的主要任务是写出对象实例变量的数值,如果变量是另一个对象的引用,则引用的对象也要串行化。这个过程是递归的
•     对象流
?c     能够输入输出对象的流称为对象流。
?c     可以将对象串行化后通过对象输入输出流写入文件或传送到其它地方
在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

扫描关注微信公众号