亚洲av成人无遮挡网站在线观看,少妇性bbb搡bbb爽爽爽,亚洲av日韩精品久久久久久,兔费看少妇性l交大片免费,无码少妇一区二区三区

  免費注冊 查看新帖 |

Chinaunix

  平臺 論壇 博客 文庫
最近訪問板塊 發(fā)新帖
查看: 1594 | 回復(fù): 0
打印 上一主題 下一主題

IO流的使用 [復(fù)制鏈接]

論壇徽章:
0
跳轉(zhuǎn)到指定樓層
1 [收藏(0)] [報告]
發(fā)表于 2008-08-09 23:45 |只看該作者 |倒序瀏覽
第八章 輸入輸出流
【課前思考】
1. 字節(jié)流和字符流的基類各是什么?
2. 什么是對象的串行化?對象串行化的作用是什么?
【學(xué)習(xí)目標】
本講主要講述了java語言中的輸入/輸出的處理,通過本講的學(xué)習(xí),同學(xué)們可以編寫更為完善的java程序。
【學(xué)習(xí)指南】
仔細閱讀本章各知識點的內(nèi)容, 深刻理解 java 語言中輸入/輸出流的處理方法,掌握處理問題的方法,多練習(xí),多上機。
【難 重 點】
 遇到實際問題時,要根據(jù)需要正確使用各種輸入/輸出流,特別是對中文使用適當(dāng)?shù)淖址斎肓鳌?br />  正確使用對象串行化的方法。
 處理字符流時,其構(gòu)造方法的參數(shù)是一個字節(jié)流。
 對象串行化的概念。
【知 識 點】
 I/O 流概述
 文件處理
 過濾流
 字符流的處理
 對象的串行化
 其它常用的流
【內(nèi) 容】
第一節(jié) 數(shù)據(jù)流的基本概念
 理解數(shù)據(jù)流
流一般分為輸入流(Input Stream)和輸出流(Output Stream)兩類,但這種劃分并不是絕對的。比如一個文件,當(dāng)向其中寫數(shù)據(jù)時,它就是一個輸出流;當(dāng)從其中讀取數(shù)據(jù)時,它就是一個輸入流。當(dāng)然,鍵盤只是一個數(shù)人流,而屏幕則只是一個輸出流。
 Java的標準數(shù)據(jù)流
標準輸入輸出指在字符方式下(如DOS),程序與系統(tǒng)進行交互的方式,分為三種:
標準輸入studin,對象是鍵盤。
標準輸出stdout,對象是屏幕。
標準錯誤輸出stderr,對象也是屏幕。
例 8.1 從鍵盤輸入字符。
本例用System.in.read(buffer)從鍵盤輸入一行字符,存儲在緩沖區(qū)buffer中,count保存實際讀入的字節(jié)個數(shù),再以
整數(shù)和字符兩種方式輸出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]; //輸入緩沖區(qū)
int count = System.in.read(buffer); //讀取標準輸入流
System.out.println("Output: ");
for (int i=0;i0)) //讀取輸入流
{
System.out.print(new String(buffer));
}
System.out.println();
rf.close(); //關(guān)閉輸入流
}
catch (IOException ioe)
{
System.out.println(ioe);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
例 8.3 寫入文件。
本例用System.in.read(buffer)從鍵盤輸入一行字符,存儲在緩沖區(qū)buffer中,再以FileOutStream的write(buffer)方法,將buffer中內(nèi)容寫入文件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");
//創(chuàng)建文件輸出流對象
wf.write(buffer,0,count); //寫入輸出流
wf.close(); //關(guān)閉輸出流
System.out.println("Save to Write1.txt!");
}
catch (IOException ioe)
{
System.out.println(ioe);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
第三節(jié) 文件操作
 File類
File類聲明如下:
public class File ectends Object implements Serializable,Comparable
構(gòu)造方法:
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); //將當(dāng)前文件名更名為給定文件的完整路徑
文件屬性測試
 boolean exists( ); //測試當(dāng)前File對象所指示的文件是否存在
 boolean canWrite( );//測試當(dāng)前文件是否可寫
 boolean canRead( );//測試當(dāng)前文件是否可讀
 boolean isFile( ); //測試當(dāng)前文件是否是文件(不是目錄)
 boolean isDirectory( ); //測試當(dāng)前文件是否是目錄
普通文件信息和工具
 long lastModified( );//得到文件最近一次修改的時間
 long length( ); //得到文件的長度,以字節(jié)為單位
 boolean delete( ); //刪除當(dāng)前文件
目錄操作
 boolean mkdir( ); //根據(jù)當(dāng)前對象生成一個由該對象指定的路徑
 String list( ); //列出當(dāng)前目錄下的文件
例 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"; //待復(fù)制的文件名
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); //當(dāng)前目錄中創(chuàng)建文件對象f1
child = new File(childdir); //當(dāng)前目錄中創(chuàng)建文件對象child
if (f1.exists())
{
if (!child.exists()) //child不存在時創(chuàng)建子目錄
child.mkdir();
f2 = new File(child,fname); //在子目錄child中創(chuàng)建文件f2
if (!f2.exists() || //f2不存在時或存在但日期較早時
f2.exists()&&(f1.lastModified() > f2.lastModified()))
copy(f1,f2); //復(fù)制
getinfo(f1);
getinfo(child);
}
else
System.out.println(f1.getName()+" file not found!");
}
public void copy(File f1,File f2) throws IOException
{ //創(chuàng)建文件輸入流對象
FileInputStream rf = new FileInputStream(f1);
FileOutputStream wf = new FileOutputStream(f2);
//創(chuàng)建文件輸出流對象
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(); //關(guān)閉輸入流
wf.close(); //關(guān)閉輸出流
}
public static void getinfo(File f1) throws IOException
{
SimpleDateFormat sdf;
sdf= new SimpleDateFormat("yyyy年MM月dd日hh時mm分");
if (f1.isFile())
System.out.println("\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 D:\myjava\Write1.txt 6 2002年12月11日02時18分
D:\myjava\backup
D:\myjava\backup\Write1.txt 6 2002年12月31日05時13分
 文件過濾器
類FilterInputStream和FilterOutputStream分別對其他輸入/輸出流進行特殊處理,它們在讀/寫數(shù)據(jù)的同時可以對數(shù)據(jù)進行特殊處理。另外還提供了同步機制,使得某一時刻只有一個線程可以訪問一個輸入/輸出流
類FilterInputStream和FilterOutputStream分別重寫了父類InputStream和OutputStream的所有方法,同時,它們的子類也應(yīng)該重寫它們的方法以滿足特定的需要
· 要使用過濾流,首先必須把它連接到某個輸入/輸出流上,通常在構(gòu)造方法的參數(shù)中指定所要連接的流:
? FilterInputStream(InputStream in);
? FilterOutputStream(OutputStream out);
這兩個類是抽象類,構(gòu)造方法也是保護方法
類BufferedInputStream和BufferedOutputStream實現(xiàn)了帶緩沖的過濾流,它提供了緩沖機制,把任意的I/O流“捆綁”到緩沖流上,可以提高讀寫效率
· 在初始化時,除了要指定所連接的I/O流之外,還可以指定緩沖區(qū)的大小。缺省大小的緩沖區(qū)適合于通常的情形;最優(yōu)的緩沖區(qū)大小常依賴于主機操作系統(tǒng)、可使用的內(nèi)存空間以及機器的配置等;一般緩沖區(qū)的大小為內(nèi)存頁或磁盤塊等地整數(shù)倍,如8912字節(jié)或更小。
? BufferedInputStream(InputStream in[, int size])
? BufferedOutputStream(OutputStream out[, int size])
例 8.5 列出當(dāng)前目錄中帶過濾器的文件名清單。
本例實現(xiàn)FilenameFilter接口中的accept方法,在當(dāng)前目錄中列出帶過濾器的文件名。
程序如下:
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[])
{ //創(chuàng)建帶通配符的文件名過濾器對象
FilenameFilter filter = new DirFilter("w*abc.txt");
File f1 = new File("");
File curdir = new File(f1.getAbsolutePath(),""); //當(dāng)前目錄
System.out.println(curdir.getAbsolutePath());
String[] str = curdir.list(filter); //列出帶過濾器的文件名清單
for (int i=0;i<str.length;i++)
System.out.println("\t"+str);
}
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;
}
}
程序運行時,列出當(dāng)前目錄中符合過濾條件“w*.txt“的文件名清單。結(jié)果如下:
D:\myjava
Write1.txt
Write2.txt
 文件對話框
 隨機文件操作
于InputStream 和OutputStream
來說,它們的實例都是順序訪問流,也就是說,只能對文件進行順序地讀/寫。隨機訪問文件則允許對文件內(nèi)容進行隨機讀/寫。在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:順序?qū)懳募?br /> · RandomAccessFile:提供對文件的隨機訪問支持
類RandomAccessFile則允許對文件內(nèi)容同時完成讀和寫操作,它直接繼承Object,并且同時實現(xiàn)了接口DataInput和DataOutput,提供了支持隨機文件操作的方法
 DataInput和DataOutput中的方法
· readInt(), writeDouble()…
 int skipBytes(int n):將指針鄉(xiāng)下移動若干字節(jié)
 length():返回文件長度
 long getFilePointer():返回指針當(dāng)前位置
 void seek(long pos):將指針調(diào)到所需位置
 void setLength(long newLength):設(shè)定文件長度
構(gòu)造方法:
RandomAccessFile(File file, String mode)
RandomAccessFile(String name, String mode)
mode 的取值
? “r” 只讀. 任何寫操作都將拋出IOException。
? “rw” 讀寫. 文件不存在時會創(chuàng)建該文件,文件存在時,原文件內(nèi)容不變,通過寫操作改變文件內(nèi)容。
? “rws” 同步讀寫. 等同于讀寫,但是任何協(xié)操作的內(nèi)容都被直接寫入物理文件,包括文件內(nèi)容和文件屬性。
? “rwd” 數(shù)據(jù)同步讀寫. 等同于讀寫,但任何內(nèi)容寫操作都直接寫到物理文件,對文件屬性內(nèi)容的修改不是這樣。
例 8.6 隨機文件操作。
本例對一個二進制整數(shù)文件實現(xiàn)訪問操作當(dāng)以可讀寫方式“rw“打開一個文件”prinmes.bin“時,如果文件不存在,將創(chuàng)建一個新文件。先將2作為最小素數(shù)寫入文件,再依次測試100以內(nèi)的奇數(shù),將每次產(chǎn)生一個素數(shù)寫入文件尾。
程序如下:
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");//創(chuàng)建文件對象
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(); //關(guān)閉文件
}
public boolean isPrime(int k) throws IOException
{
int i=0,j;
boolean yes = true;
try
{
raf.seek(0);
int count = (int)(raf.length()/4); //返回文件字節(jié)長度
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)+" 個素數(shù):");
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();
}
}
程序運行時創(chuàng)建文件“primes.bin“,并將素數(shù)寫入其中,結(jié)果如下:
[2..100]中有 25 個素數(shù):
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
第四節(jié) 字符流
Reader類和Writer類
前面說過,在JDK1.1之前,java.io包中的流只有普通的字節(jié)流(以byte為基本處理單位的流),這種流對于以16位的Unicode
碼表示的字符流處理很不方便。從JDK1.1開始,
java.io包中加入了專門用于字符流處理的類,它們是以Reader和Writer為基礎(chǔ)派生的一系列類
同類InputStream和OutputStream一樣,Reader和Writer也是抽象類,只提供了一系列用于字符流處理的接口。它們的方法與類InputStream和OutputStream類似,只不過其中的參數(shù)換成字符或字符數(shù)組
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 文件編輯器。
本例實現(xiàn)文件編輯器中的打開、保存文件功能。程序如下:
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)); //設(shè)置文本行的初始字體
f.add(tf1,"North");
ta1 = new TextArea();
ta1.setFont(new Font("Dialog",0,20)); //設(shè)置文本區(qū)的初始字體
f.add(ta1);
ta1.addTextListener(this); //注冊文本區(qū)的事件監(jiān)聽程序
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); //注冊按鈕的事件監(jiān)聽程序
b2.addActionListener(this);
b3.addActionListener(this);
f.add(p1,"South");
f.setVisible(true);
}
public void textValueChanged(TextEvent e)
{ //實現(xiàn)TextListener接口中的方法,對文本區(qū)操作時觸發(fā)
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); //創(chuàng)建并顯示打開文件對話框
if ((fd.getDirectory()!=null) && (fd.getFile()!=null))
{
tf1.setText(fd.getDirectory()+fd.getFile());
try //以緩沖區(qū)方式讀取文件內(nèi)容
{
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); //創(chuàng)建并顯示保存文件對話框
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 //將文本區(qū)內(nèi)容寫入字符輸出流
{
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);
}
}
第五節(jié) 字節(jié)流的高級應(yīng)用
 管道流
管道用來把一個程序、線程和代碼塊的輸出連接到另一個程序、線程和代碼塊的輸入。java.io中提供了類PipedInputStream和PipedOutputStream作為管道的輸入/輸出流
管道輸入流作為一個通信管道的接收端,管道輸出流則作為發(fā)送端。管道流必須是輸入輸出并用,即在使用管道前,兩者必須進行連接
管道輸入/輸出流可以用兩種方式進行連接:
? 在構(gòu)造方法中進行連接
· PipedInputStream(PipedOutputStream pos);
· PipedOutputStream(PipedInputStream pis);
? 通過各自的connect()方法連接
· 在類PipedInputStream中,connect(PipedOutputStream pos);
· 在類PipedOutputStream中,connect(PipedInputStream pis);
例 8.8 管道流。
本例例管道流的使用方法。設(shè)輸入管道in與輸出管道out已連接,Send線程向輸出管道out發(fā)送數(shù)據(jù),Receive線程從輸入管道in中接收數(shù)據(jù)。程序如下:
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 //發(fā)送線程
{
PipedOutputStream out;
static int count=0; //記錄線程個數(shù)
int k=0;
public Send(PipedOutputStream out,int k)
{
this.out= out;
this.k= k;
this.count++; //線程個數(shù)加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(); //關(guān)閉輸入管道流
System.out.println(" out closed!");
}
else
this.count--; //線程個數(shù)減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) //輸入流未結(jié)束時
{
System.out.print(i+" ");
i = in.read();
sleep(1);
}
in.close(); //關(guān)閉輸入管道流
}
catch(InterruptedException e) { }
catch(IOException e)
{
System.out.println(e);
}
}
}
程序運行結(jié)果如下:
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!
 數(shù)據(jù)流
DataInputStream和DataOutputStream
 在提供了字節(jié)流的讀寫手段的同時,
 以統(tǒng)一的通用的形式向輸入流中寫入boolean,int,long,double等基本數(shù)據(jù)類型,并可以在次把基本數(shù)據(jù)類型的值讀取回來。
 提供了字符串讀寫的手段。
 分別實現(xiàn)了DataInput和DataOutput接口
聲明類:
Public class DataInputStream extends filterInputStream implements DataInput
例 8.9 數(shù)據(jù)流。
本例演示數(shù)據(jù)流的使用方法。
程序如下:
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
{ //添加方式創(chuàng)建文件輸出流
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) //輸入流未結(jié)束時
{
System.out.print(i+" ");
char ch ;
while ((ch=din.readChar())!=´\n´) //字符串未結(jié)束時
System.out.print(ch);
System.out.println();
i = din.readInt();
}
din.close();
}
catch (IOException ioe){}
}
}
程序運行結(jié)果如下:
1 Wang
2 Li
 對象流
· 對象的持續(xù)性(Persistence)
? 能夠紀錄自己的狀態(tài)一邊將來再生的能力,叫對象的持續(xù)性
· 對象的串行化(Serialization)
? 對象通過寫出描述自己狀態(tài)的的數(shù)值來記錄自己的過程叫串行化。串行化的主要任務(wù)是寫出對象實例變量的數(shù)值,如果變量是另一個對象的引用,則引用的對象也要串行化。這個過程是遞歸的
· 對象流
? 能夠輸入輸出對象的流稱為對象流。
? 可以將對象串行化后通過對象輸入輸出流寫入文件或傳送到其它地方
在java中,允許可串行化的對象在通過對象流進行傳輸。只有實現(xiàn)Serializable接口的類才能被串行化, Serializable接口中沒有任何方法,當(dāng)一個類聲明實現(xiàn)Serializable接口時,只是表明該類加入對象串行化協(xié)議
要串行化一個對象,必須與一定的對象輸出/輸入流聯(lián)系起來,通過對象輸出流將對象狀態(tài)保存下來(將對象保存到文件中,或者通過網(wǎng)絡(luò)傳送到其他地方) ,再通過對象輸入流將對象狀態(tài)恢復(fù)
類ObjectOutputStream和ObjectInputStream分別繼承了接口ObjectOutput和
ObjectInput,將數(shù)據(jù)流功能擴展到可以讀寫對象,前者用writeObject()方法可以直接將對象保存到輸出流中,而后者用
readObject()方法可以直接從輸入流中讀取一個對象
例 8.10 對象流。
本例聲明Student2為序列化的類。Save方法中,創(chuàng)建對象輸出流out,并以添加方式向文件中直接寫入當(dāng)前對象
out.writeObject(this);display方法中,創(chuàng)建對象輸入流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);
}
}
程序運行結(jié)果如下:
Student2 interface java.io.Serializable
1 Wang
               
               
               

本文來自ChinaUnix博客,如果查看原文請點:http://blog.chinaunix.net/u2/66950/showart_1119436.html
您需要登錄后才可以回帖 登錄 | 注冊

本版積分規(guī)則 發(fā)表回復(fù)

  

北京盛拓優(yōu)訊信息技術(shù)有限公司. 版權(quán)所有 京ICP備16024965號-6 北京市公安局海淀分局網(wǎng)監(jiān)中心備案編號:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年舉報專區(qū)
中國互聯(lián)網(wǎng)協(xié)會會員  聯(lián)系我們:huangweiwei@itpub.net
感謝所有關(guān)心和支持過ChinaUnix的朋友們 轉(zhuǎn)載本站內(nèi)容請注明原作者名及出處

清除 Cookies - ChinaUnix - Archiver - WAP - TOP