Java進階核心之InputStream流深入講解
IO: Input / Ouput 即輸入輸出
輸出流:程序(內(nèi)存) —>外界設(shè)備 輸入流:外界設(shè)備—>程序(內(nèi)存)處理理數(shù)據(jù)類型分類
字符流:處理字符相關(guān),如處理文本數(shù)據(jù)(如txt文件), Reader/Writer 字節(jié)流: 處理字節(jié)相關(guān),如聲音或者圖片等二進制,InputStream/OutputStream兩者區(qū)別:
字節(jié)流以字節(jié)(8bit)為單位,字符流以字符為單位,根據(jù)碼表映射字符,一次可能讀多個字節(jié) 字節(jié)流可以處理幾乎所有文件,字符流只能處理字符類型的數(shù)據(jù)功能不同,但是具有共性內(nèi)容,通過不斷抽象形成4個抽象類,抽象類下面有很多子類是具體的實現(xiàn)
字符流 Reader/Writer 字節(jié)流 InputStream/OutputStreamIO流相關(guān)類體系概覽
InputStream是輸入字節(jié)流的父類,它是一個抽象類(一般用他的子類)
int read()講解:從輸⼊入流中讀取單個字節(jié),返回0到255范圍內(nèi)的int字節(jié)值,字節(jié)數(shù)據(jù)可直接轉(zhuǎn)換為int類型, 如果已經(jīng)到達流末尾⽽而沒有可⽤用的字節(jié),則返回- 1int read(byte[] buf)講解:從輸⼊入流中讀取⼀一定數(shù)量量的字節(jié),并將其存儲在緩沖區(qū)數(shù)組buf中, 返回實際讀取的字節(jié)數(shù),如果已經(jīng)到達流末尾⽽而沒有可⽤用的字節(jié),則返回- 1long skip(long n)講解:從輸⼊入流中跳過并丟棄 n 個字節(jié)的數(shù)據(jù)。int available()講解:返回這個流中有多少個字節(jié)數(shù),可以把buf數(shù)組⻓長度定為這個void close() throws IOException講解:關(guān)閉輸⼊入流并釋放與該流關(guān)聯(lián)的系統(tǒng)資源
常見子類
FilelnputStream
抽象類InputStream用來具體實現(xiàn)類的創(chuàng)建對象,文件字節(jié)輸入流,對文件數(shù)據(jù)以字節(jié)的形式進行讀取操作 常用構(gòu)造函數(shù)//傳⼊入⽂文件所在地址public FileInputStream(String name) throws FileNotFoundException//傳⼊入⽂文件對象public FileInputStream(File file) throws FileNotFoundException
例如:
package domee.chapter10_2;import java.io.*;public class Main { public static void main(String[] args)throws IOException { String dir = 'C:Users阮相歌Desktoptest'; String name = 'a.txt'; File file = new File(dir,name); InputStream inputStream = new FileInputStream(file); testRead(inputStream); testSkip(inputStream); testReadByteArr(inputStream); } public static void testReadByteArr(InputStream inputStream)throws IOException{ //如果buf的長度為0,則不讀取任何字節(jié)并返回0;每次讀取的字節(jié)數(shù)最多等于buf的長度 //byte[] buf = new byte[1024]; byte[] buf = new byte[inputStream.available()]; int length; //循環(huán)讀取文件內(nèi)容,輸入流中將最多的buf.length // 個字節(jié)數(shù)據(jù)讀入一個buf數(shù)組中,返回類型是讀取到的字節(jié)數(shù) //如果這個緩沖區(qū)沒有滿的話,則返回真實的字節(jié)數(shù) while ((length = inputStream.read(buf))!= -1){ //中文亂碼問題,換成GBK,或者UTF-8 System.out.print(new String(buf,0,length)); System.out.print(new String(buf,0,length,'UTF-8')); System.out.println(new String(buf,0,length)); } } public static void testRead(InputStream inputStream)throws IOException{ //對于漢字等 unicode中的字符不能正常讀取,只能以亂碼的形式顯示 int read = inputStream.read(); System.out.println(read); System.out.println((char)read); } public static void testSkip(InputStream inputStream)throws IOException{ long skipSize = inputStream.skip(2); System.out.println(skipSize); int read = inputStream.read(); System.out.println(read); System.out.println((char)read); }}
編碼小知識(節(jié)省空間)
操作的中文內(nèi)容多則推薦GBK:
GBK中英文也是兩個字節(jié),用GBK節(jié)省了空間,UTF-8編碼的中文使用了三個字節(jié)o如果是英文內(nèi)容多則推薦UFT-8:
因為UFT-8里面英文只占一個字節(jié) UTF-8編碼的中文使用了三個字節(jié)總結(jié)到此這篇關(guān)于Java進階核心之InputStream流的文章就介紹到這了,更多相關(guān)Java InputStream流內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
