Java基礎(chǔ)之IO流

流就是當(dāng)不同的介質(zhì)之間有數(shù)據(jù)交互的時候,JAVA就使用流來實現(xiàn)认罩。數(shù)據(jù)源可以是文件,還可以是數(shù)據(jù)庫续捂,網(wǎng)絡(luò)甚至是其他的程序垦垂,比如讀取文件的數(shù)據(jù)到程序中,站在程序的角度來看牙瓢,就叫做輸入流

字節(jié)流:

字節(jié)輸入流: InputStream

字節(jié)輸出流:OutputStream

以字節(jié)流的方式讀取文件:

public?class?TestStream {

????public?static?void?main(String[] args) {

????????try?{

?????//準(zhǔn)備文件lol.txt其中的內(nèi)容是AB劫拗,對應(yīng)的ASCII分別是65 66

????????????File f =new?File("d:/lol.txt");

????????????//創(chuàng)建基于文件的輸入流

????????????FileInputStream fis =new?FileInputStream(f);

????????????//創(chuàng)建字節(jié)數(shù)組,其長度就是文件的長度

????????????byte[] all =new?byte[(int) f.length()];

????????????//以字節(jié)流的形式讀取文件所有內(nèi)容

????????????fis.read(all);

????????????for?(byte?b : all) {

????????????????//打印出來是65 66

????????????????System.out.println(b);

????????????}?

????????????//每次使用完流矾克,都應(yīng)該進行關(guān)閉

????????????fis.close();?

????????}?catch?(IOException e) {

????????????// TODO Auto-generated catch block

????????????e.printStackTrace();

????????}??

????}

}

以字節(jié)流的方式向文件寫數(shù)據(jù):

public?class?TestStream {

????public?static?void?main(String[] args) {

????????try?{

????????????// 準(zhǔn)備文件lol2.txt其中的內(nèi)容是空的

????????????File f =?new?File("d:/lol2.txt");

??// 準(zhǔn)備長度是2的字節(jié)數(shù)組页慷,用88,89初始化,其對應(yīng)的字符分別是X,Y

????????????byte?data[] = {?88,?89?};

????????????// 創(chuàng)建基于文件的輸出流

????????????FileOutputStream fos =?new?FileOutputStream(f);

????????????// 把數(shù)據(jù)寫入到輸出流

????????????fos.write(data);

????????????// 關(guān)閉輸出流

????????????fos.close();?????????

????????}?catch?(IOException e) {

????????????// TODO Auto-generated catch block

????????????e.printStackTrace();

????????}

????}

}

流的關(guān)閉方式有3種:1胁附、try中關(guān)閉 2酒繁、finally中關(guān)閉 3、使用try()方式關(guān)閉

1控妻、在try的作用域里關(guān)閉文件輸入流州袒,一般在開發(fā)中經(jīng)常使用,這樣做有一個弊端饼暑;

如果文件不存在稳析,或者讀取的時候出現(xiàn)問題而拋出異常,那么就不會執(zhí)行這一行關(guān)閉流的代碼弓叛,存在巨大的資源占用隱患彰居。?不推薦使用

public?class?TestStream {

????public?static?void?main(String[] args) {

????????try?{

????????????File f =?new?File("d:/lol.txt");

????????????FileInputStream fis =?new?FileInputStream(f);

????????????byte[] all =?new?byte[(int) f.length()];

????????????fis.read(all);

????????????for?(byte?b : all) {

????????????????System.out.println(b);

????????????}

????????????// 在try 里關(guān)閉流

????????????fis.close();

????????}?catch?(IOException e) {

????????????e.printStackTrace();

????????}

????}

}

2、這是標(biāo)準(zhǔn)的關(guān)閉流的方式

(1)首先把流的引用聲明在try的外面撰筷,如果聲明在try里面陈惰,其作用域無法抵達finally.

(2)在finally關(guān)閉之前,要先判斷該引用是否為空

(3)關(guān)閉的時候毕籽,需要再一次進行try catch處理

這是標(biāo)準(zhǔn)的嚴謹?shù)年P(guān)閉流的方式抬闯,但是看上去很繁瑣井辆,所以寫不重要的或者測試代碼的時候,都會采用上面的有隱患try的方式溶握,因為不麻煩

public?class?TestStream {

????public?static?void?main(String[] args) {

????????File f =?new?File("d:/lol.txt");

????????FileInputStream fis =?null;

????????try?{

????????????fis =?new?FileInputStream(f);

????????????byte[] all =?new?byte[(int) f.length()];

????????????fis.read(all);

????????????for?(byte?b : all) {

????????????????System.out.println(b);

????????????}

????????}?catch?(IOException e) {

????????????e.printStackTrace();

????????}?finally?{

????????????// 在finally 里關(guān)閉流

????????????if?(null?!= fis)

????????????????try?{

????????????????????fis.close();

????????????????}?catch?(IOException e) {

????????????????????// TODO Auto-generated catch block

????????????????????e.printStackTrace();

????????????????}

????????}

????}

}

3杯缺、把流定義在try()里,try,catch或者finally結(jié)束的時候,會自動關(guān)閉睡榆,這種編寫代碼的方式叫做?try-with-resources萍肆, 這是從JDK7開始支持的技術(shù),所有的流胀屿,都實現(xiàn)了一個接口叫做?AutoCloseable塘揣,任何類實現(xiàn)了這個接口,都可以在try()中進行實例化宿崭。并且在try, catch, finally結(jié)束的時候自動關(guān)閉亲铡,回收相關(guān)資源。

public?class?TestStream {

????public?static?void?main(String[] args) {

????????File f =?new?File("d:/lol.txt");

????????//把流定義在try()里,try,catch或者finally結(jié)束的時候葡兑,會自動關(guān)閉

????????try?(FileInputStream fis =?new?FileInputStream(f)) {

????????????byte[] all =?new?byte[(int) f.length()];

????????????fis.read(all);

????????????for?(byte?b : all) {

????????????????System.out.println(b);

????????????}

????????}?catch?(IOException e) {

????????????e.printStackTrace();

????????}

????}

}

字符流:

字符輸入流:Reader

字符輸出流:Writer

使用字符流讀取文件:

public?class?TestStream {

????public?static?void?main(String[] args) {

????????// 準(zhǔn)備文件lol.txt其中的內(nèi)容是AB

????????File f =?new?File("d:/lol.txt");

????????// 創(chuàng)建基于文件的Reader

????????try?(FileReader fr =?new?FileReader(f)) {

????????????// 創(chuàng)建字符數(shù)組奖蔓,其長度就是文件的長度

????????????char[] all =?new?char[(int) f.length()];

????????????// 以字符流的形式讀取文件所有內(nèi)容

????????????fr.read(all);

????????????for?(char?b : all) {

????????????????// 打印出來是A B

????????????????System.out.println(b);

????????????}

????????}?catch?(IOException e) {

????????????// TODO Auto-generated catch block

????????????e.printStackTrace();

????????}

????}

}

使用字符流把字符串寫入到文件:

public?class?TestStream {

????public?static?void?main(String[] args) {

????????// 準(zhǔn)備文件lol2.txt

????????File f =?new?File("d:/lol2.txt");

????????// 創(chuàng)建基于文件的Writer

????????try?(FileWriter fr =?new?FileWriter(f)) {

????????????// 以字符流的形式把數(shù)據(jù)寫入到文件中

????????????String data="abcdefg1234567890";

????????????char[] cs = data.toCharArray();

????????????fr.write(cs);

????????}?catch?(IOException e) {

????????????// TODO Auto-generated catch block

????????????e.printStackTrace();

????????}

????}

}

緩存流:

緩存字符輸入流BufferedReader, 可以一次讀取一行數(shù)據(jù)

緩存字符輸出流PrintWriter?铁孵, 可以一次寫出一行數(shù)據(jù)

使用緩存字符輸入流讀取文件:

public?class?TestStream {

????public?static?void?main(String[] args) {

????????// 準(zhǔn)備文件lol.txt其中的內(nèi)容是

????????// garen kill teemo

????????// teemo revive after 1 minutes

????????// teemo try to garen, but killed again

????????File f =?new?File("d:/lol.txt");

????????// 創(chuàng)建文件字符流

????????// 緩存流必須建立在一個存在的流的基礎(chǔ)上

????????try?(

????????????????FileReader fr =?new?FileReader(f);

????????????????BufferedReader br =?new?BufferedReader(fr);

????????????)

????????{

????????????while?(true) {

????????????????// 一次讀一行

????????????????String line = br.readLine();

????????????????if?(null?== line)

????????????????????break;

????????????????System.out.println(line);

????????????}

????????}?catch?(IOException e) {

????????????// TODO Auto-generated catch block

????????????e.printStackTrace();

????????}

????}

}

使用緩存流寫出數(shù)據(jù):

public?class?TestStream {

????public?static?void?main(String[] args) {

????????// 向文件lol2.txt中寫入三行語句

????????File f =?new?File("d:/lol2.txt");

????????try?(

????????????????// 創(chuàng)建文件字符流

????????????????FileWriter fw =?new?FileWriter(f);

????????????????// 緩存流必須建立在一個存在的流的基礎(chǔ)上??????????????

????????????????PrintWriter pw =?new?PrintWriter(fw);??????????????

????????) {

????????????pw.println("garen kill teemo");

????????????pw.println("teemo revive after 1 minutes");

????????????pw.println("teemo try to garen, but killed again");

????????}?catch?(IOException e) {

????????????// TODO Auto-generated catch block

????????????e.printStackTrace();

????????}

????}

}

有的時候锭硼,需要立即把數(shù)據(jù)寫入到硬盤,而不是等緩存滿了才寫出去蜕劝。 這時候就需要用到flush

public?class?TestStream {

????public?static?void?main(String[] args) {

????????//向文件lol2.txt中寫入三行語句

????????File f =new?File("d:/lol2.txt");

????????//創(chuàng)建文件字符流

????????//緩存流必須建立在一個存在的流的基礎(chǔ)上

????????try(FileWriter fr =?new?FileWriter(f);PrintWriter pw =?new?PrintWriter(fr);) {

????????????pw.println("garen kill teemo");

????????????//強制把緩存中的數(shù)據(jù)寫入硬盤檀头,無論緩存是否已滿

????????????????pw.flush();???????????

????????????pw.println("teemo revive after 1 minutes");

????????????????pw.flush();

????????????pw.println("teemo try to garen, but killed again");

????????????????pw.flush();

????????}?catch?(IOException e) {

????????????// TODO Auto-generated catch block

????????????e.printStackTrace();

????????}

????}

}

數(shù)據(jù)流:

DataInputStream 數(shù)據(jù)輸入流?

DataOutputStream 數(shù)據(jù)輸出流

使用數(shù)據(jù)流進行讀寫:

public?class?TestStream {

????public?static?void?main(String[] args) {

????????write();

????????read();

????}

????private?static?void?read() {

????????File f =new?File("d:/lol.txt");

????????try?(

????????????????FileInputStream fis? =?new?FileInputStream(f);

????????????????DataInputStream dis =new?DataInputStream(fis);

????????){

????????????boolean?b= dis.readBoolean();

????????????int?i = dis.readInt();

????????????String str = dis.readUTF();

????????????System.out.println("讀取到布爾值:"+b);

????????????System.out.println("讀取到整數(shù):"+i);

????????????System.out.println("讀取到字符串:"+str);

????????}?catch?(IOException e) {

????????????e.printStackTrace();

????????}

????}

????private?static?void?write() {

????????File f =new?File("d:/lol.txt");

????????try?(

????????????????FileOutputStream fos? =?new?FileOutputStream(f);

????????????????DataOutputStream dos =new?DataOutputStream(fos);

????????){

????????????dos.writeBoolean(true);

????????????dos.writeInt(300);

????????????dos.writeUTF("123 this is gareen");

????????}?catch?(IOException e) {

????????????e.printStackTrace();

????????}

????}

}

對象流:是可以直接把一個對象以流的形式傳輸給其他的介質(zhì),比如硬盤岖沛,一個對象以流的形式進行傳輸暑始,叫做序列化。 該對象所對應(yīng)的類婴削,必須是實現(xiàn)Serializable接口

學(xué)生類實現(xiàn)Serializable

public class Student implements Serializable{

????????public String name;

????????public int age;

}

public class TextFileObject {

????public static void main(String[] args) {

????//創(chuàng)建一個學(xué)生對象

????//要把Student對象直接保存在文件上廊镜,務(wù)必讓Student類實現(xiàn)Serializable接口

????Student stu = new Student();

????stu.name="小王";

????stu.age=18;

????//準(zhǔn)備一個文件用于保存該對象

????File f = new File("d:/hero.txt");

????//創(chuàng)建對象輸出流

????try(FileOutputStream fos = new FileOutputStream(f);

????ObjectOutputStream oos = new ObjectOutputStream(fos);

????//創(chuàng)建對象輸入流

????FileInputStream fis = new FileInputStream(f);

????ObjectInputStream ois = new ObjectInputStream(fis);){

????oos.writeObject(stu);

????Student s = (Student) ois.readObject();

????System.out.println(s.name);

????System.out.println(s.age);

????} catch (Exception e) {

????// TODO: handle exception

}

}

}

System.in

public?class?TestStream {

????public?static?void?main(String[] args) {

????????// 控制臺輸入

????????try?(InputStream is = System.in;) {

????????????while?(true) {

????????????????// 敲入a,然后敲回車可以看到

????????????????// 97 13 10

????????????????// 97是a的ASCII碼

????????????????// 13 10分別對應(yīng)回車換行

????????????????int?i = is.read();

????????????????System.out.println(i);

????????????}

????????}?catch?(IOException e) {

????????????e.printStackTrace();

????????}

????}

}

使用Scanner讀取

public?class?TestStream {

????public?static?void?main(String[] args) {

????????????Scanner s =?new?Scanner(System.in);

????????????while(true){

????????????????String line = s.nextLine();

????????????????System.out.println(line);

????????????}

????}

}

使用Scanner從控制臺讀取整數(shù)

public?class?TestStream {

????public?static?void?main(String[] args) {

????????Scanner s =?new?Scanner(System.in);

????????int?a = s.nextInt();

????????System.out.println("第一個整數(shù):"+a);

????????int?b = s.nextInt();

????????System.out.println("第二個整數(shù):"+b);

????}

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市唉俗,隨后出現(xiàn)的幾起案子嗤朴,更是在濱河造成了極大的恐慌,老刑警劉巖虫溜,帶你破解...
    沈念sama閱讀 218,941評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件雹姊,死亡現(xiàn)場離奇詭異,居然都是意外死亡衡楞,警方通過查閱死者的電腦和手機吱雏,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人歧杏,你說我怎么就攤上這事镰惦。” “怎么了犬绒?”我有些...
    開封第一講書人閱讀 165,345評論 0 356
  • 文/不壞的土叔 我叫張陵旺入,是天一觀的道長。 經(jīng)常有香客問我凯力,道長眨业,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,851評論 1 295
  • 正文 為了忘掉前任沮协,我火速辦了婚禮,結(jié)果婚禮上卓嫂,老公的妹妹穿的比我還像新娘慷暂。我一直安慰自己,他們只是感情好晨雳,可當(dāng)我...
    茶點故事閱讀 67,868評論 6 392
  • 文/花漫 我一把揭開白布行瑞。 她就那樣靜靜地躺著,像睡著了一般餐禁。 火紅的嫁衣襯著肌膚如雪血久。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,688評論 1 305
  • 那天帮非,我揣著相機與錄音氧吐,去河邊找鬼。 笑死末盔,一個胖子當(dāng)著我的面吹牛筑舅,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播陨舱,決...
    沈念sama閱讀 40,414評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼翠拣,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了游盲?” 一聲冷哼從身側(cè)響起误墓,我...
    開封第一講書人閱讀 39,319評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎益缎,沒想到半個月后谜慌,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,775評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡链峭,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年畦娄,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,096評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡熙卡,死狀恐怖杖刷,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情驳癌,我是刑警寧澤滑燃,帶...
    沈念sama閱讀 35,789評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站颓鲜,受9級特大地震影響表窘,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜甜滨,卻給世界環(huán)境...
    茶點故事閱讀 41,437評論 3 331
  • 文/蒙蒙 一乐严、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧衣摩,春花似錦昂验、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至泡嘴,卻和暖如春甫恩,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背酌予。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評論 1 271
  • 我被黑心中介騙來泰國打工磺箕, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人抛虫。 一個月前我還...
    沈念sama閱讀 48,308評論 3 372
  • 正文 我出身青樓滞磺,卻偏偏與公主長得像,于是被迫代替她去往敵國和親莱褒。 傳聞我的和親對象是個殘疾皇子击困,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,037評論 2 355

推薦閱讀更多精彩內(nèi)容