java IO 位元組流、字元流操作總結二之位元組流

來源:互聯網
上載者:User

上一篇,主要介紹了檔案類File和RandomAccessFile類的用法。接下來,我覺得還是將IO流分為位元組流和字元流兩部分介紹比較好。這樣不至於搞混亂,同時也便於對比。這一篇主要介紹位元組流。

1、位元組流

首先上一張位元組流的家族圖譜。


位元組流主要分為兩部分:InputStream、OutputStream。InputStream抽象了應用程式讀取資料的方式,OutputStream抽象了應用程式寫出資料的方式。

注意有時會碰到EOF(即End Of File),表示已經讀完。讀到-1時表示讀到檔案的結尾。

a、InputStream輸入資料流基本的操作方法

int b=in.read();讀一個位元組,無符號填充到int低八位,-1表示EOF。in.read(byte[]buf);讀取資料填充到位元組數組buf中in.read(byte[]buf,int start,int size);讀取資料到位元組數組buf。然後從buf的start位置開始存放size長度的資料

b、OutputStream輸出資料流本操作方法

out.write(intb);寫一個byte到流中,寫的內容是b的低8位out.write(byte[]buf);將一個buf位元組數組都寫入到流out.write(byte[]buf,int start,int size);位元組數組buf從start位置開始寫size長度的位元組到流。

c、FileInputStream 具體實現了檔案上的讀取檔案

註:1>單位元組的讀取即不用數組,在讀取大檔案時效率較低。

       2>批量的讀取,對於大檔案而言效率較高,也是我們最常用的讀取檔案的方式。

       3>byte類型8位,int類型為32位,為了避免資料類型的轉換的錯誤。通過0xff將高24為清零。

       4>read()適合單位元組的讀取大小

in.read(byte[] buf,int start,int size);位元組數組適合讀取大檔案 

d、FileOutputStream實現向檔案中寫出byte資料的方法。

檔案輸出資料流的寫法:

FileOutputStream  output=new FileOutputStream(file,true);//這個方法表示檔案若不存在,則建立新的檔案,若存在則在後面新增內容。FileOutputStream  output=new FileOutputStream(file);//這個方法表示檔案不存在就建立新檔案,若檔案存在則先刪除檔案然後再建立檔案。

在執行完output.write(byte[] buf,int start,int size)之後,一定要調用output.flush()方法來重新整理緩衝區。 

測試代碼如下:

package com.ll.iofile;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;/** * 這個方法是用來測試字元流的 * 主要用到是InputStreamReader 字元輸出資料流 * OutputStreamWriter  * @author LULEI * */public class testInputStreamReaderAndOutputStreamWriter {public static void main(String[] args) throws IOException{// TODO Auto-generated method stub/*這是測試第一個例子 * 就是將gbk編碼的檔案複製成utf-8格式的檔案FileInputStream in=new FileInputStream("DEMO\\fileio1.txt");InputStreamReader isr=new InputStreamReader(in);//此處預設項目的編碼是gbk的*//*這是測試第一個例子 * 就是將gbk編碼的檔案複製成utf-8格式的檔案FileOutputStream out=new FileOutputStream("Demo\\OutputStreamUTF8.txt");OutputStreamWriter osw=new OutputStreamWriter(out,"utf-8");*/FileInputStream in=new FileInputStream("C:\\Users\\Administrator\\Desktop\\OutputStreamUTF8.txt");InputStreamReader isr=new InputStreamReader(in,"utf8");//這樣的寫法就是設定為utf8編碼FileOutputStream out=new FileOutputStream("Demo\\OutputStreamGBK.txt");OutputStreamWriter osw=new OutputStreamWriter(out);//預設的編碼就是gbkint c=0;/*這是單位元組的輸出while((c=isr.read())!=-1){System.out.print((char)c);}*/char[] buf=new char[20*1024];while((c=isr.read(buf, 0, buf.length))!=-1){//String str=new String(buf);//System.out.println(str);osw.write(buf,0,c);osw.flush();}isr.close();osw.close();}}

e、 資料輸入輸出資料流

它是位元組流的一個拓展。它是用來協助方便操作類型資料的。

1>  包含DataOutputStream和DataInputStream

2>  對“流“功能的擴充,可以更加方便的讀取int,long,字元等類型資料。

3>  DataOutputStream的方法:

writeInt()/writeDouble()/writeUTF()

4>  DataInputStream的方法:

readInt()/readDouble()/readUTF()

代碼如下:

package com.ll.iofile;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.lang.reflect.Array;import java.util.Arrays;/** * 這個類用於測試資料的輸入輸出資料流 * 即DataOutputStream 和DataInputStream * @author LULEI * */public class testDataOutputStreamAndDataInputStream {public static void main(String[] args) throws IOException{// TODO Auto-generated method stub//測試DataOutputStream類String str="Demo\\wq77.txt";DataOutputStream dos=new DataOutputStream(new FileOutputStream(str));//執行個體化一個對象dos.write(10);//佔一個位元組dos.writeInt(-10);//寫一個int型整數,佔4個位元組dos.writeDouble(10.8);//佔8個位元組//以UTF-8的格式寫入字串dos.writeUTF("中國");//一個漢子佔3個位元組//以utf-16be的格式寫入字串dos.writeChars("中國");//一個漢字佔2個位元組dos.close();//列印輸出的檔案的位元組IOUtils.printHexByByte(str);System.out.println();//執行個體化資料輸入流對象DataInputStream dif=new DataInputStream(new FileInputStream(str));int a=dif.read();System.out.println(a);int b=dif.readInt();System.out.println(b);double d=dif.readDouble();System.out.println(d);String s1=dif.readUTF();System.out.println(s1);byte[] bytes=new byte[6];dif.read(bytes);System.out.println(Arrays.toString(bytes));//轉換為字串顯示dif.close();}}

f、BufferedInputStream&BufferedOutputStream(帶有緩衝區的輸入輸出資料流)

這兩個流位於IO提供了帶有緩衝區的操作,一般開啟檔案進行寫入或讀取操作時,都會加上緩衝,這種流模式提高了IO的效能。從應用程式中把輸入放入檔案,相當於將一缸水倒入另一個缸中。

1>  FileOutputStream:write方法相當於一滴一滴的把水轉移過去。

2>  DataOutputStream:writeXXX方法會方便一些,相當於一瓢一瓢的把水轉移過去

3>  BufferedOutputStream:write()方法會更方便一些,相當於一瓢一瓢先放入水桶中,在從桶中倒入缸中,效能提高了。

代碼如下:

package com.ll.iofile;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;/* * 這個函數是為了測試BufferedOutputStream、FileOutputStream、DataOutputStream * 這三個類在copy檔案時的速度快慢 */public class testBufferedOutputStreamAndBufferedInputStream {public static void main(String[] args) throws IOException{// TODO Auto-generated method stubFile file=new File("C:\\Users\\Administrator\\Desktop\\浪潮之巔.pdf");long start1=System.currentTimeMillis();FileToCopyByByte(file);long end1=System.currentTimeMillis();System.out.println(end1-start1);long start2=System.currentTimeMillis();FileToCopy(file);long end2=System.currentTimeMillis();System.out.println(end2-start2);long start3=System.currentTimeMillis();DataToCopy(file);long end3=System.currentTimeMillis();System.out.println(end3-start3);long start4=System.currentTimeMillis();bufferedFileToCopy(file);long end4=System.currentTimeMillis();System.out.println(end4-start4);}public static void FileToCopyByByte(File file)throws IOException{if(!file.exists()){System.out.println("檔案"+file+"不存在");}if(!file.isFile()){System.out.println("檔案"+file+"不是檔案");}FileInputStream fis=new FileInputStream(file);//執行個體化讀取位元組的檔案流//執行個體化寫位元組檔案流FileOutputStream fos =new FileOutputStream("Demo\\fileIoByByte1.pdf");int b=0;while((b=fis.read())!=-1){fos.write(b);}fis.close();fos.close();}public static void FileToCopy(File file)throws IOException{if(!file.exists()){System.out.println("檔案"+file+"不存在");}if(!file.isFile()){System.out.println("檔案"+file+"不是檔案");}FileInputStream fis=new FileInputStream(file);//執行個體化讀取位元組的檔案流//執行個體化寫位元組檔案流FileOutputStream fos =new FileOutputStream("Demo\\fileio1.pdf"); int length=0; byte[] buf=new byte[20*1024];  while((length=fis.read(buf, 0, buf.length))!=-1){ fos.write(buf);// fos.flush(); }fis.close();fos.close();}public static void DataToCopy(File dateFile)throws IOException{if(!dateFile.exists()){System.out.println("檔案"+dateFile+"不存在");}if(!dateFile.isFile()){System.out.println("檔案"+dateFile+"不是檔案");}//執行個體化一個讀取檔案的對象DataInputStream dis=new DataInputStream(new FileInputStream(dateFile));//執行個體化一個寫檔案的對象DataOutputStream dos=new DataOutputStream(new FileOutputStream("Demo\\datafile1.pdf"));int length=0;byte[] buf=new byte[20*1024];while((length=dis.read(buf, 0, buf.length))!=-1){dos.write(buf);//dos.flush();}//關閉檔案dis.close();dos.close();}public static void bufferedFileToCopy(File bufferedFile)throws IOException{if(!bufferedFile.exists()){System.out.println("檔案"+bufferedFile+"不存在");}if(!bufferedFile.isFile()){System.out.println("檔案"+bufferedFile+"不是檔案");}BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("Demo\\bufferedfile1.pdf"));BufferedInputStream bis=new BufferedInputStream(new FileInputStream(bufferedFile));int length=0;byte[] buf=new byte[20*1024];while((length=bis.read(buf, 0, buf.length))!=-1){bos.write(buf);bos.flush();}bis.close();bos.close();}}

到這裡我只是簡單的介紹了一些常用的位元組流。比如FileInputStream和FileOutputStream。聰明的你會知道這裡又是使用了裝飾器類設計模式。哈哈,下次別人提到裝飾器設計模式,你就說IO流的實現。下一篇我講介紹字元流的知識。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.