Java I/O的典型使用方式

來源:互聯網
上載者:User

標籤:int   main   img   adb   pack   leo   iter   style   多少   

前面已經介紹了IO的各種流,我們知道,可以通過不同的方式組合I/O流。介紹幾種典型的I/O的使用方法;

1.緩衝檔案讀取

開啟一個檔案,並讀取其中的字元,可以使用String或者file對象作為檔案名稱的FileInputReader.

如下:

package IOStreamTest;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;public class BufferdInputFile {        public static String read(String filepath) throws IOException{        FileReader filere = new FileReader(new File(filepath));        int ch;        StringBuilder sb = new StringBuilder();        while((ch=filere.read())!=-1){            sb.append(ch);            System.out.println(ch);        }        filere.close();        return sb.toString();    }   public static void main(String args[]) throws IOException{       System.out.println(read("fortest"));          }}

輸入檔案: fortest 

 

 

只能一個字元一個字元的讀取 結果如下,輸出:

 

為了提高速度,可以使用BufferedReader來讀取 ,如下所示:

package IOStreamTest;import java.io.BufferedReader;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;public class BufferdInputFile {        public static String read(String filepath) throws IOException{        BufferedReader bufre = new BufferedReader(new FileReader(new File(filepath)));        StringBuilder sb = new StringBuilder();        String s;        int ch=0;        while((ch=bufre.read())!=-1){            sb.append(ch);        }    /*    while((s=bufre.readLine())!=null)            sb.append(s+"\n");*/        bufre.close();        return sb.toString();            }   public static void main(String args[]) throws IOException{       System.out.println(read("fortest"));          }}

結果與一樣。

Bufferreader提供readline方法,而filereader只提供

A  ,int read(); // 讀取單個字元。返回作為整數讀取的字元,如果已達到流末尾,則返回 -1。

B. int read(char []cbuf);//將字元讀入數組。返回讀取的字元數。如果已經到達尾部,則返回-1 

2從記憶體中輸入

從BufferedInputFile.read中讀入的String用來建立一個Stringreader然後調用read每次讀取一個字元,並發送到控制台。

public static void main(String args[]) throws IOException{       StringReader sr = new StringReader(BufferdInputFile.read("fortest"));       int ch=0;       while((ch=sr.read())!=-1){           System.out.print((char)ch);//注意read是以int形式返回下一位元組,因此要轉化成char才能正確列印。       }       //System.out.println(read("fortest"));          }

3.格式化的記憶體輸入

要讀取格式化的資料,可以使用DataInputStream,這個是面向位元組的IO.因此使用inputstream而不是reader.

public static void main(String args[]) throws IOException{       DataInputStream datain = new  DataInputStream               (new ByteArrayInputStream(BufferdInputFile.read("fortest").getBytes()));       while(datain.available()!=0){        //由於readbyte一次讀取一個字元,任何位元組的值都是合法的結果,因此傳回值不能用來檢驗輸入是否結束。相反,我們可以利用available()
//還有多少個供存取的字元檢查 System.out.println((
char)datain.readByte()); } }

4.基本的檔案輸出

filewriter向檔案寫入資料。通常,建立一個與指定檔案連結的filewriter 實際上,會用bufferedwriter封裝起來用來緩衝輸出。可以根據需要將其封裝成任意輸出資料流。在此封裝城printwriter

在javase5中,可以省略掉裝飾工作。添加了輔助構造器(PrintWriter pw = new printwirter(file)).printwriter 可以格式化資料方便閱讀。

import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.io.PrintWriter;import java.io.StringReader;public class BufferedOutputtest {    public static void main(String args[]) throws IOException{        BufferedReader bufr =new BufferedReader(new StringReader(BufferdInputFile.read("read")));        PrintWriter pw = new PrintWriter                //(new File("fortest"));                (new BufferedWriter(new FileWriter("fortest")));        int linecount =1;        String s;        while((s=bufr.readLine())!=null)            pw.println(linecount++ +":"+s);        pw.close();        //System.out.println(BufferdInputFile.read("fortest"));    }}

5.儲存和恢複資料

可以從dataoutputStream寫入資料,並用datastream恢複資料。

Java保證我們可以使用datainputstream準確的讀取資料,無論讀寫的平台有多麼不一樣。

package IOStreamTest;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;public class dataout_inputstream {    public static void main(String args[]) throws IOException{    DataOutputStream datao =new DataOutputStream(new BufferedOutputStream(new FileOutputStream("fortest")));    datao.writeInt(9);    datao.writeUTF("mark");    datao.writeByte(9);    datao.close();   DataInputStream datain  = new DataInputStream(new BufferedInputStream(new FileInputStream("fortest")));   System.out.println(datain.readInt());   System.out.println(datain.readUTF());    }}

6.讀寫隨機訪問檔案。RandomAccessFile

類似於組合使用了dataoutput 和datainputstream。

Random適合由大小已知的記錄組成的檔案。可以用seek將記錄從一處轉移到另一處。實現了datainput和dataoutput介面,不是繼承自outputstream或者inputstream。支援搜尋方法,可以查詢當點所處的檔案位置(getfilepointer());

 

7.管道流。用於多任務間的通訊,也就是說用於並發。pipeinputstream pipeoutputstream,pipereader piperwriter等等。

 

 

 

 

 

Java I/O的典型使用方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.