IO流-----(位元組流)

來源:互聯網
上載者:User

標籤:int   char   throws   瞭解   []   ring   方法   try   inf   

以stream結尾的稱為萬能流(位元組流),否則為字元流

1.java流的概述:

  檔案通常是由一串的位元組或字元組成,組成檔案的位元組序列稱為位元組流,組成檔案的字元序列稱為字元流。

2.Java中根據流的方向可以分為:輸入資料流和輸出資料流

  輸入資料流:輸入資料流是將檔案或其他輸入裝置的資料載入到記憶體的過程

  輸出資料流:輸出資料流是將記憶體中的資料儲存到檔案或其他輸入裝置中

 

??????3.檔案是由位元組或字元構成,那麼將檔案載入到記憶體或者將檔案輸出到檔案,需要輸入資料流和輸出資料流的支援,那麼在JAVA語言中又把輸入和輸出資料流分為兩種:

                        位元組輸入資料流、位元組輸出資料流            字元輸入資料流、字元輸出資料流

 

3.1 Inputstream(位元組輸入資料流):inputstream是一個抽象的類,所有實現了inputstream類的都是位元組輸入資料流,主要瞭解一下子類即可:

 

 

範例:

public class Test{

  public static void main(String[] args) throws Exception{

  //建立一個輸入資料流

  InputStream in=new FileInputStream("c:/a.txt");

  //定義一個臨時變數

  int temp=0;

  while((temp=in.read())!=-1){

  System.out.println((char)temp);

    }

  }

}

3.2 OutputStream(位元組輸出資料流):OutputStream是一個抽象的類,所有實現了這個類的都是位元組輸出資料流

如果調用了close()方法,那麼會自動調用flush()方法,但是建議手動顯示的去調用flush()方法

範例:

public class Test {

  public static void main(String[] args) {
  //建立一個輸出位元組流
  OutputStream out = null;
  try {
    out = new FileOutputStream("c:/b.txt");
    out.write(123);
    //必須調用flush或close
    out.flush();
  } catch (Exception e) {
    e.printStackTrace();
  }finally {
    try {
      out.close();
    } catch (IOException e) {
      e.printStackTrace();
      }
    }
  System.out.println("success");
  }
}

jdk1.8新特性自動關閉:

範例:

public class Test{

  public static void main(String[] args){

  try(OutputSreeam out =new FileOutputStream("c:/c.txt");){

  //建立一個輸出位元組流

  out.write(1);

  //必須調用flush方法

  out.flush();

  }catch(Exception e){

  e.printStackTrace();

  }

  System.out.println(success);

  }  

}

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.