很多朋友都想知道java fileinputstream的作用有哪些?下面就一起來了解一下吧~
FileInputStream作用
FileInputStream主要用于讀取文件,將文件信息讀到內(nèi)存中。
FileInputStream構(gòu)造方法
構(gòu)造方法有三個(gè),常用的有以下兩個(gè):
1、FileInputStream(File file),參數(shù)傳入一個(gè)File類型的對(duì)象。
2、FileInputStream(String name),參數(shù)傳入文件的路徑。
FileInputStream常用方法
1、int read()方法
從文件的第一個(gè)字節(jié)開始,read方法每執(zhí)行一次,就會(huì)將一個(gè)字節(jié)讀取,并返回該字節(jié)ASCII碼,如果讀出的數(shù)據(jù)是空的,即讀取的地方是沒有數(shù)據(jù),則返回-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?{ //流是空的時(shí)候不能關(guān)閉,否則會(huì)空指針異常? if(fis!=null)?{ try?{ fis.close(); }?catch?(IOException?e)?{ e.printStackTrace(); } } } } 文件a中存儲(chǔ)了abcd四個(gè)字母,讀出結(jié)果也是abcd。
2、int read(byte b[])該方法與int read()方法不一樣,該方法將字節(jié)一個(gè)一個(gè)地往byte數(shù)組中存放,直到數(shù)組滿或讀完,然后返回讀到的字節(jié)的數(shù)量,如果**一個(gè)字節(jié)都沒有讀到,則返回-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,讀出結(jié)果是abcde。System.out.print(new String(b,0,readCount));是為了將讀到的字節(jié)輸出,如果直接輸出b數(shù)組,則最后一次只讀了de,但數(shù)組原來的第三個(gè)元素是c,最后輸出結(jié)果就變成了:abcdec
FileInputStream的其他方法
1、int available();獲取文件中還可以讀的字節(jié)(剩余未讀的字節(jié))的數(shù)量。
作用:可以直接定義一個(gè)文件總字節(jié)數(shù)量的Byte數(shù)組,一次就把文件所有字節(jié)讀到數(shù)組中,就可以不使用循環(huán)語句讀。 但這種方式不適合大文件,因?yàn)閿?shù)組容量太大會(huì)耗費(fèi)很多內(nèi)存空間。
2、long skip(long n);將光標(biāo)跳過n個(gè)字節(jié)。
以上就是小編今天的分享,希望可以幫到大家。