很多朋友都想知道java fileinputstream的作用有哪些?下面就一起來了解一下吧~
FileInputStream作用
FileInputStream主要用于讀取文件,將文件信息讀到內存中。
FileInputStream構造方法
構造方法有三個,常用的有以下兩個:
1、FileInputStream(File file),參數傳入一個File類型的對象。
2、FileInputStream(String name),參數傳入文件的路徑。
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個字節。
以上就是小編今天的分享,希望可以幫到大家。