Java基礎知識回顧之六 ----- IO流

來源:互聯網
上載者:User

標籤:system.in   puts   stat   部落格   分享圖片   其它   使用   關閉   它的   

前言

在上一篇文章中,回顧了Java的多線程。而在本篇文章中主要介紹Java IO的相關知識。

IO的介紹

什麼是IO?

IO的名稱又來是Input與Output的縮寫,也就是輸入資料流和輸出資料流。輸入資料流用於從源讀取資料,輸出資料流用於向目標寫資料。

可以從下列樣本圖來瞭解IO流:

IO流使用

IO流對檔案的操作主要分為字元流和位元組流。

字元流

字元流有兩個抽象類別:Writer和Reader類。
其對應子類FileWriter和FileReader可實現檔案的讀寫操作。
BufferedWriter和BufferedReader能夠提供緩衝區功能,用以提高效率。

我記得在開始學習Java不久的時候, 在教程中會使用 字元流來進行字元的讀取和寫入。比較常見的就是,運行一個main方法,然後再控制台輸入字元,擷取輸入的字元做一些邏輯控制之類。
例如: 在控制台輸入字元,輸入quit退出,輸入其它的字元列印。

程式碼範例:

    public static void main(String[] args)  {        try {            test();        } catch (IOException e) {            e.printStackTrace();        }    }    private static void test() throws IOException {          String str;            // 使用 System.in 建立 BufferedReader             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));            System.out.println("輸入字元, 輸入 'quit' 退出。");            // 讀取字元            do {               str=br.readLine();               System.out.println("您輸入的字元是:"+str);            } while(!str.equals("quit"));             br.close();    }

然後我們輸入 hello 和quit。
結果如下:

輸入字元, 輸入 'quit' 退出。hello您輸入的字元是:hello您輸入的字元是:quit您輸入的字元是:quit

通過上述樣本我們可以簡單的瞭解下了字元流。
一般來說,我們主要用字元流的情況是讀寫檔案,大部分也是文字檔,比如.txt尾碼的。這裡我們也順便介紹下如何使用。

程式碼範例:

    /**     *     * 寫入和讀取檔案     * @throws IOException     */    private static void test2() throws IOException {        //建立要操作的檔案路徑和名稱          String path ="E:/test/hello.txt";        String str="hello world";        FileWriter fw = new FileWriter(path);          fw.write(str);          fw.close();                  FileReader fr = new FileReader(path);          StringBuffer sb=new StringBuffer();        while(fr.ready()){            sb.append((char)fr.read());        }        System.out.println("輸出:"+sb.toString());        fr.close();    }

註:如果在不同的系統上運行,可以使用 File.separator方法,該方法表示系統的分隔字元。

輸出結果:

輸出:hello word

上述程式碼範例中,我們使用FileWriter 和FileReader 這兩個類對檔案進行讀寫,雖然可以實現字元的寫入和讀取,但是效率並不高,因為是對磁碟的直接讀寫。一般對於檔案的讀寫,我們會使用緩衝。使用緩衝的好處就像 倒垃圾一樣,將垃圾進行整理堆積,然後到了一定的規模在丟棄,而不是有一點垃圾就倒一次。

那麼在上述的代碼中加上BufferedWriter和BufferedReader類來進行緩衝。

程式碼範例:

    /**     * 寫入和讀取檔案     * @throws IOException     */    private static void test3() throws IOException {        //建立要操作的檔案路徑和名稱          String path ="E:/test/hello.txt";        String str="你好!";        FileWriter fw = new FileWriter(path);          BufferedWriter bw=new BufferedWriter(fw);        bw.write(str);          bw.close();        fw.close();                  FileReader fr = new FileReader(path);          BufferedReader br=new BufferedReader(fr);        StringBuffer sb=new StringBuffer();        while(br.ready()){            sb.append((char)br.read());        }        System.out.println("輸出:"+sb.toString());        br.close();        fr.close();    }

注:需要注意的是關閉的順序,先關閉緩衝,再關閉檔案。

位元組流

位元組流也有兩個抽象類別:InputStream和OutputStream類。
其對應子類有FileInputStream和FileOutputStream實現檔案讀寫操作。
BufferedInputStream和BufferedOutputStream提供緩衝區功能

位元組流也能對文本進行讀取,但是它的主要使用的情境是讀取無法直接擷取文本資訊的二進位檔案,比如音樂檔案、視頻檔案、圖片檔案等等。
這裡我們依舊對檔案進行讀取和寫入,不過我們把之前寫入到hello.txt檔案的內容加上 ‘你好‘ 寫入到新的檔案中。由於這裡使用的了中文,所以需要設定相應的編碼。

程式碼範例:

 /**     * 建立一個檔案並讀取記錄      * @throws IOException     */    private static void test4() throws IOException {        String path="E:/test/hello.txt";        String path2="E:/test/你好.txt";        String str="你好!";        //從檔案讀取資料        InputStream input = new FileInputStream(path);        InputStreamReader reader = new InputStreamReader(input, "UTF-8");        StringBuffer sb=new StringBuffer();        while(reader.ready()){            sb.append((char)reader.read());        }                input.close();        reader.close();                //建立一個檔案並向檔案中寫資料        OutputStream output = new FileOutputStream(path2);        OutputStreamWriter writer = new OutputStreamWriter(output, "UTF-8");        writer.write(sb+str);                writer.close();        output.close();                //從檔案讀取資料        InputStream input2 = new FileInputStream(path2);        InputStreamReader reader2 = new InputStreamReader(input2, "UTF-8");        StringBuffer sb2=new StringBuffer();        while(reader2.ready()){            sb2.append((char)reader2.read());        }        System.out.println("輸出:"+sb2);        input2.close();        reader2.close();    }   

結果:

    輸出:hello world你好!

可以看到結果符合我們的預期。

File

學習IO流中,我們也會接觸File類。
File類中主要是對檔案夾的一些操作。比如,檔案夾的建立、刪除、查看等等。
這裡我們就簡單的介紹下File類的相關使用,還是使用代碼配合注釋來進行說明。

程式碼範例:

private static void test5() throws IOException {        String path="E:/test/test2";        String path2="E:/test/test3/test3";        String path3="E:/test/test2/test2.txt";        File f = new File(path);        File f2 = new File(path2);        File f3 = new File(path3);        //建立檔案夾        System.out.println("="+f.mkdir());        //建立檔案夾和所有父資料夾        System.out.println("=="+f2.mkdirs());        //建立一個文本        System.out.println("==="+f3.createNewFile());        //擷取名稱        System.out.println("==="+f3.getName());        //擷取父級名稱        System.out.println("==="+f3.getParent());        //擷取當前路徑        System.out.println("==="+f3.getPath());        //判斷是否是目錄        System.out.println("=="+f2.isDirectory());        System.out.println("==="+f3.isDirectory());        //刪除該檔案        System.out.println("==="+f3.delete());  }   

輸出結果:

=true==true===true===test2.txt===E:\test\test2===E:\test\test2\test2.txt==true===false===true

關於File類的相關只是簡單的介紹了下,具體的使用還需要配置實際的情境。需要注意的是,在進行檔案建立和刪除的時候,需要先判斷是否存在,否則將拋出異常。

其它

到此,本文就結束了,謝謝閱讀!歡迎留言和點贊,你的支援是我寫作最大的動力!

著作權聲明:
虛無境
部落格園出處:http://www.cnblogs.com/xuwujing
CSDN出處:http://blog.csdn.net/qazwsxpcm    
個人部落格出處:http://www.panchengming.com

Java基礎知識回顧之六 ----- 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.