java.io源碼解析(二)--文件操作(FileInputStream蹄葱、FileOutputStream、FileReader锄列、FileWriter)

聲明:本系列只供本人自學(xué)使用图云,勿噴。

實(shí)際開發(fā)中最常用的就是文件IO邻邮,通常情況下竣况,操作二進(jìn)制文件用字節(jié)流,文本文件用字符流筒严。

一丹泉、文件字節(jié)流

1.FileInputStream

  • 構(gòu)造器
//實(shí)際調(diào)用FileInputStream(File file)
public FileInputStream(String name) throws FileNotFoundException
public FileInputStream(File file) throws FileNotFoundException{
    1.文件安全及權(quán)限檢查
    2.創(chuàng)建FileDescriptor實(shí)例來表示文件連接
    3.native方法open
}
// 使用文件系統(tǒng)的現(xiàn)有文件連接來創(chuàng)建
public FileInputStream(FileDescriptor fdObj)
  • 核心方法

核心:私有的本地readBytes方法

private native int readBytes(byte b[], int off, int len) throws IOException;

public int read(byte b[]) throws IOException
public int read(byte b[], int off, int len)

public void close() throws IOException
  • 其他方法
public native long skip(long n) throws IOException;
public native int available() throws IOException;
public final FileDescriptor getFD() throws IOException
public FileChannel getChannel()

2.FileOutputStream

  • 構(gòu)造器
//實(shí)際調(diào)用FileOutputStream(File file, boolean append) 
public FileOutputStream(String name) throws FileNotFoundException
public FileOutputStream(String name, boolean append)
public FileOutputStream(File file) throws FileNotFoundException

public FileOutputStream(File file, boolean append) throws FileNotFoundException{
    1.文件安全及權(quán)限檢查
    2.創(chuàng)建FileDescriptor實(shí)例來表示文件連接
    3.native方法open
}
// 使用文件系統(tǒng)的現(xiàn)有文件連接來創(chuàng)建
public FileOutputStream(FileDescriptor fdObj)
  • 核心方法

核心:私有的本地writeBytes方法

private native void writeBytes(byte b[], int off, int len, boolean append)

public void write(byte b[]) throws IOException
public void write(byte b[], int off, int len)

public void close() throws IOException
  • 其他方法
public final FileDescriptor getFD() throws IOException
public FileChannel getChannel()

3.demo

最常見的功能:用FileInputStream和FileOutputStream復(fù)制文件

注:JDK7新增try-with-resources語法,將資源放入try()內(nèi)萝风,就不用手動close()了嘀掸。

    try (
                InputStream is = new FileInputStream("D:\\fileTest\\app.properties");
                // InputStream is=new FileInputStream(new File("D:\\fileTest\\app.properties"));
                OutputStream os = new FileOutputStream("D:\\fileTest\\out.properties");
        ) {
            byte[] bytes=new byte[1024];
            int len=0;
            while ((len=is.read(bytes))!=-1){
                os.write(bytes,0,len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

二紫岩、文件字符流

在研究FileReader和FileWriter之前规惰,有必要先了解其父類。

1.InputStreamReader

底層StreamDecoder

  • 構(gòu)造器(必須以InputStream為入?yún)ⅲ?/strong>
// 實(shí)際調(diào)用 StreamDecoder的構(gòu)造器
public InputStreamReader(InputStream in)
public InputStreamReader(InputStream in, String charsetName)
public InputStreamReader(InputStream in, Charset cs)
public InputStreamReader(InputStream in, CharsetDecoder dec)
  • 核心方法

核心:read到字符數(shù)組

public int read(char cbuf[], int offset, int length) throws IOException

public int read() throws IOException

public void close() throws IOException
  • 其他方法
public boolean ready() throws IOException
public String getEncoding()

2.FileReader

本質(zhì):給定默認(rèn)字符集與buffer大小的InputStreamReader

  • 構(gòu)造器
public FileReader(String fileName) throws FileNotFoundException
public FileReader(File file) throws FileNotFoundException
public FileReader(FileDescriptor fd)

3.OutputStreamWriter

底層StreamEncoder

  • 構(gòu)造器(必須以O(shè)utputStream為入?yún)ⅲ?/strong>
// 實(shí)際調(diào)用 StreamEncoder的構(gòu)造器
public OutputStreamWriter(OutputStream out)
public OutputStreamWriter(OutputStream out, String charsetName)
public OutputStreamWriter(OutputStream out, Charset cs)
public OutputStreamWriter(OutputStream out, CharsetEncoder enc)
  • 核心方法

核心:將字符數(shù)組write到輸出流

public void write(String str, int off, int len) throws IOException
public void write(char cbuf[], int off, int len) throws IOException
public void write(int c) throws IOException

public void flush() throws IOException{
    1.flushBuffer()
    2.flush輸出流
}
public void close() throws IOException
  • 其他方法
void flushBuffer() throws IOException
public String getEncoding()

4.FileWriter

本質(zhì):給定默認(rèn)字符集與buffer大小的OutputStreamWriter

  • 構(gòu)造器
public FileWriter(String fileName) throws IOException
public FileWriter(String fileName, boolean append) throws IOException
public FileWriter(File file) throws IOException
public FileWriter(File file, boolean append) throws IOException
public FileWriter(FileDescriptor fd)

5.demo

功能1:用FileReader和FileWriter復(fù)制文本文件

注:和上述的字節(jié)流傳輸代碼相似泉蝌,只是換成用char[]傳輸歇万,因此需要的話可以自行輸出方便閱讀的chars

    try(
                FileReader fileReader=new FileReader("D:\\fileTest\\app.properties");
                FileWriter fileWriter=new FileWriter("D:\\fileTest\\out2.properties")
        ) {
            char[] chars=new char[1024];
            int len=0;
            while ((len=fileReader.read(chars))!=-1){
                fileWriter.write(chars,0,len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

功能2:用InputStreamReader讀取properties

InputStreamReader reader=new InputStreamReader(new FileInputStream("D:\\fileTest\\app.properties"));
Properties properties=new Properties();
properties.load(reader);
properties.forEach((k,v)-> System.out.println(k+":"+v));

三、總結(jié)

本節(jié)研究了基礎(chǔ)的文件操作類勋陪,包括字節(jié)流FileInputStream贪磺、FileOutputStream,字符流InputStreamReader及其子類FileReader诅愚,OutputStreamWriter及其子類FileWriter寒锚,注意文件字符流必須通過字節(jié)流來構(gòu)造,這些類都可以實(shí)現(xiàn)讀寫文件,一般情況下我們使用字節(jié)流讀寫二進(jìn)制文件刹前,字符流讀寫文本文件(比如properties等包含中文的配置文件)泳赋。

下一節(jié)我們將探討使用較頻繁的Object流。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末喇喉,一起剝皮案震驚了整個濱河市祖今,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌拣技,老刑警劉巖千诬,帶你破解...
    沈念sama閱讀 217,734評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異膏斤,居然都是意外死亡徐绑,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評論 3 394
  • 文/潘曉璐 我一進(jìn)店門莫辨,熙熙樓的掌柜王于貴愁眉苦臉地迎上來泵三,“玉大人,你說我怎么就攤上這事衔掸√棠唬” “怎么了?”我有些...
    開封第一講書人閱讀 164,133評論 0 354
  • 文/不壞的土叔 我叫張陵敞映,是天一觀的道長较曼。 經(jīng)常有香客問我,道長振愿,這世上最難降的妖魔是什么捷犹? 我笑而不...
    開封第一講書人閱讀 58,532評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮冕末,結(jié)果婚禮上萍歉,老公的妹妹穿的比我還像新娘。我一直安慰自己档桃,他們只是感情好枪孩,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,585評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著藻肄,像睡著了一般蔑舞。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上嘹屯,一...
    開封第一講書人閱讀 51,462評論 1 302
  • 那天攻询,我揣著相機(jī)與錄音,去河邊找鬼州弟。 笑死钧栖,一個胖子當(dāng)著我的面吹牛低零,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播拯杠,決...
    沈念sama閱讀 40,262評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼毁兆,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了阴挣?” 一聲冷哼從身側(cè)響起气堕,我...
    開封第一講書人閱讀 39,153評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎畔咧,沒想到半個月后茎芭,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,587評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡誓沸,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,792評論 3 336
  • 正文 我和宋清朗相戀三年梅桩,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片拜隧。...
    茶點(diǎn)故事閱讀 39,919評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡宿百,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出洪添,到底是詐尸還是另有隱情垦页,我是刑警寧澤,帶...
    沈念sama閱讀 35,635評論 5 345
  • 正文 年R本政府宣布干奢,位于F島的核電站痊焊,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏忿峻。R本人自食惡果不足惜薄啥,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,237評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望逛尚。 院中可真熱鬧垄惧,春花似錦、人聲如沸绰寞。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽克握。三九已至蕾管,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間菩暗,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評論 1 269
  • 我被黑心中介騙來泰國打工旭蠕, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留停团,地道東北人旷坦。 一個月前我還...
    沈念sama閱讀 48,048評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像佑稠,于是被迫代替她去往敵國和親秒梅。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,864評論 2 354