資源描述:
《輸入輸出字符流_1ppt課件》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在教育資源-天天文庫。
1、處理壓縮文件壓縮流類java.util.zip包中提供了一些類,使我們可以以壓縮格式對(duì)流進(jìn)行讀寫它們都繼承自字節(jié)流類OutputStream和InputStream其中GZIPOutputStream和ZipOutputStream可分別把數(shù)據(jù)壓縮成GZIP格式和Zip格式GZIPInputStream和ZipInputStream可以分別把壓縮成GZIP格式或Zip的數(shù)據(jù)解壓縮恢復(fù)原狀GZIPOutputStream父類是DeflaterOutputStream可以把數(shù)據(jù)壓縮成GZIP格式GZIPInputStream父類是InflaterInputStream可
2、以把壓縮成GZIP格式的數(shù)據(jù)解壓縮——簡(jiǎn)單的GZIP壓縮格式將文本文件“Hello.txt”壓縮為文件“test.gz”,再解壓該文件,顯示其中內(nèi)容,并另存為“newHello.txt”importjava.io.*;importjava.util.zip.*;publicclassTest1{publicstaticvoidmain(String[]args)throwsIOException{FileInputStreamin=newFileInputStream("c:/Hello.txt");GZIPOutputStreamout=newGZIPOutput
3、Stream(newFileOutputStream("c:/test.gz"));System.out.println("Writingcompressingfilefromc:/Hello.txttoc:/test.gz");intc;while((c=in.read())!=-1)out.write(c);//寫壓縮文件in.close();out.close();System.out.println("Readingfileformc:/test.gztomonitor");BufferedReaderin2=newBufferedReader(newInp
4、utStreamReader(newGZIPInputStream(newFileInputStream("c:/test.gz"))));Strings;while((s=in2.readLine())!=null)System.out.println(s);in2.close();System.out.println("Writingdecompressiontoc:/newHello.txt");GZIPInputStreamin3=newGZIPInputStream(newFileInputStream("c:/test.gz"));FileOutputS
5、treamout2=newFileOutputStream("c:/newHello.txt");while((c=in3.read())!=-1)out2.write(c);in3.close();out2.close();}}運(yùn)行結(jié)果首先生成了壓縮文件“test.gz”再讀取顯示其中的內(nèi)容,和“Hello.txt”中的內(nèi)容完全一樣解壓縮文件“newHello.txt”,和“Hello.txt”中的內(nèi)容也完全相同說明read()方法讀取一個(gè)字節(jié),轉(zhuǎn)化為[0,255]的之間的一個(gè)整數(shù),返回一個(gè)int。如果讀到了文件末尾,則返回-1。write(int)方法寫一個(gè)字節(jié)
6、的低8位,忽略了高24位。Zip文件可能含有多個(gè)文件,所以有多個(gè)入口(Entry)每個(gè)入口用一個(gè)ZipEntity對(duì)象表示,該對(duì)象的getName()方法返回文件的最初名稱ZipOutputStream父類是DeflaterOutputStream可以把數(shù)據(jù)壓縮成ZIP格式ZipInputStream父類是InflaterInputStream可以把壓縮成ZIP格式的數(shù)據(jù)解壓縮——運(yùn)用ZIP壓縮多個(gè)文件從命令行輸入若干個(gè)文件名,將所有文件壓縮為“test.zip”,再從此壓縮文件中解壓并顯示importjava.io.*;importjava.util.*;impo
7、rtjava.util.zip.*;publicclassTest1{publicstaticvoidmain(String[]args)throwsIOException{ZipOutputStreamout=newZipOutputStream(newBufferedOutputStream(newFileOutputStream("test.zip")));args=newString[2];args[0]="Hello.txt";args[1]="newHello.txt";for(inti=0;i