Java學習總結,java總結

來源:互聯網
上載者:User

Java學習總結,java總結

  Java類庫裡有四個表示流的抽象父類:InputStream、OutputStream、Reader、Writer。

  其中 InputStream 和 OutputStream 是對位元組進行操作的輸入資料流和輸出資料流;Reader 和 Writer 是對字元操作的輸入輸出資料流。

  它們是抽象類別,在用它們的時候必須要對其進行執行個體化,因此類庫也提供了具有不同功能的它們的子類,比如,以檔案形式輸入輸出的FileInputStream、FileOutputStream和FileReader、FileWriter等。

  --------------------------------------------------------------

  一、位元組流

  1. InputStream、OutputStream 只能進行位元組的傳輸資料

         InputStream抽象了應用程式讀取資料的方式

       OutputStream抽象了應用程式寫出資料的方式

  2. EOF = End,讀到 -1 就讀到結尾。

  3. 輸入資料流的基本方法(以下的 in 代表輸入資料流的對象)

      int b = in.read();

      從流讀取一個位元組無符號填充到int的低8位。(一個int變數是4個位元組,1位元組=8位,read()方法只能讀取一個位元組並返回int,所以該位元組填充到int的低八位。)若讀到結尾,返回 -1。

      in.read(byte[] buf);

      從流讀取資料直接填充到位元組數組buf,讀取位元組的個數取決於數組的長度。

      in.read(byte[] buf, int start, int size);

      從流讀取資料到位元組數組buf,從buf的start位置開始,存放size長度的資料。

  4. 輸出資料流的基本方法(以下的 out 代表輸出資料流的對象)

      out.write(int b);

      寫出一個byte到流,寫出的是b的低8位。

      out.write(byte[] buf);

      將一個位元組數組寫出到流。

      out.write(byte[] buf, int start, int size);

      從buf的start位置開始,寫size長度的資料到流。

  5. FileInputStream 是InputStream的子類,具體實現了在檔案上讀取資料:

package test;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;public class TestDemo {        public static void main(String[] args) throws Exception {        //我們在D盤下建立了一個demo.txt,內容為“你好hello”。        File file = new File("D:\\demo.txt");        if(!file.exists()) file.createNewFile();        InputStream in = new FileInputStream(file);        int temp;        while((temp = in.read()) != -1) {            System.out.print(Integer.toHexString(temp & 0xff) + " ");        }        in.close();        System.out.println();                InputStream in2 = new FileInputStream(file);        byte[] buf = new byte[1024];        in2.read(buf);        String s = new String(buf,"GBK");        System.out.println(s);        in2.close();    }    }
TestDemo

      Output:    c4 e3 ba c3 68 65 6c 6c 6f
              你好hello                          

 

  

 

聯繫我們

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