JAVA學習之InputStream類與FileInputStream__JAVA

來源:互聯網
上載者:User
一.InputStram類 1.類說明 首先要對java的輸入資料有一個認識,java是使用對象的形式去使用和處理輸入的資料的,但是我們的InputStream是一個抽象類別,並不能直接建立對象去儲存資料,但是我們可以通過使用InputStream的子類的形式來建立對象,因為子類的對象也可以作為父類的對象,所以可以通過InputStream類的方法來使用子類的對象。還要注意,由read()方法的聲明可知,這個方法會拋出一個IOException類型的異常,所以一定要進行異常處理。

2.類方法說明

主要方法有兩個一個是read(),功能是從輸入資料流讀入下一個字元,這裡要注意,從標準輸入資料流中讀入資料,並不是每輸入一個字元就形成一個輸入資料流,而是輸入斷行符號之後,一整行形成一個輸入資料流。

另一個是close()功能是關閉輸入資料流,並釋放資源。

3.使用樣本

import java.io.InputStream;import java.io.IOException;class echo {public echo(InputStream in) //這裡將InputStream作為形式參數使用{try<span style="white-space:pre"></span>//System.in是InputStream的子類PrintStream的執行個體對象,作為實參傳入{while(true){int temp;temp=in.read();if(temp==-1) break;System.out.print((char) temp);}}catch(IOException e){System.err.println("something is worge");}}}public class MyInputStream {public static void main(String args[]){new echo(System.in);}}

二.FileInputStream類 1.類說明 這個類不是抽象類別,可以直接建立對象來實現資料的儲存與處理。 2.類方法 這個類主要由三個重要方法,最重要的是構造方法,參數是要讀取資料的檔案,其他兩個方法是read()和close()方法使用和 3.使用樣本

import java.io.FileInputStream;import java.io.IOException;public class J_FileRead {public static void main(String args[]){try{FileInputStream f=new FileInputStream("input.txt");int b;b=f.read();while(true){System.out.print((char) b);b=f.read();if(b==-1) break;}System.out.println();f.close();}catch(Exception e){System.out.println("something is wrong!");System.exit(0);}}}


聯繫我們

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