網站首頁 學習教育 IT科技 金融知識 旅遊規劃 生活小知識 家鄉美食 養生小知識 健身運動 美容百科 遊戲知識 綜合知識
當前位置:趣知科普吧 > IT科技 > 

fileinputstream|java

欄目: IT科技 / 發佈於: / 人氣:2.08W

<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>

很多朋友都想知道java fileinputstream的作用有哪些?下面就一起來了解一下吧~

FileInputStream作用

FileInputStream主要用於讀取檔案,將檔案資訊讀到內存中。

FileInputStream構造方法

構造方法有三個,常用的有以下兩個:

1、FileInputStream(File file),參數傳入一個File類型的對象。

2、FileInputStream(String name),參數傳入檔案的路徑。

java fileinputstream

FileInputStream常用方法

1、int read()方法

從檔案的第一個字節開始,read方法每執行一次,就會將一個字節讀取,並返回該字節ASCII碼,如果讀出的數據是空的,即讀取的地方是沒有數據,則返回-1,如下列代碼:

public static void main(String[] args) {FileInputStream fis = null;try {fis=new FileInputStream("a");//開始讀int readData;while((readData=fis.read())!=-1) {System.out.println((char)readData);}}catch (IOException e) {e.printStackTrace();}finally {//流是空的時候不能關閉,否則會空指針異常 if(fis!=null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}}}檔案a中存儲了abcd四個字母,讀出結果也是abcd。

2、int read(byte b[])
該方法與int read()方法不一樣,該方法將字節一個一個地往byte數組中存放,直到數組滿或讀完,然後返回讀到的字節的數量,如果**一個字節都沒有讀到,則返回-1。**如下列代碼:

public static void main(String[] args) {FileInputStream fis = null;int readCount;try {fis=new FileInputStream("a");while((readCount=fis.read(b))!=-1) {System.out.print(new String(b,0,readCount));}}catch (IOException e) {e.printStackTrace();}finally {if(fis!=null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}}}

a檔案存的是abcde,讀出結果是abcde。
System.out.print(new String(b,0,readCount));是爲了將讀到的字節輸出,如果直接輸出b數組,則最後一次只讀了de,但數組原來的第三個元素是c,最後輸出結果就變成了:abcdec

FileInputStream的其他方法

1、int available();獲取檔案中還可以讀的字節(剩餘未讀的字節)的數量。

作用:可以直接定義一個檔案總字節數量的Byte數組,一次就把檔案所有字節讀到數組中,就可以不使用循環語句讀。 但這種方式不適合大檔案,因爲數組容量太大會耗費很多內存空間。

2、long skip(long n);將遊標跳過n個字節。

Tags:java