日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

IO流——流的分类、InputStream、OutputStream、Reader、Writer等

發(fā)布時間:2025/3/15 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 IO流——流的分类、InputStream、OutputStream、Reader、Writer等 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

一、IO流概述

流的分類

1.操作數(shù)據(jù)單位:字節(jié)流、字符流
2.數(shù)據(jù)的流向:輸入流、輸出流
3.流的角色:節(jié)點流、處理流

二、節(jié)點流 (文件流)

  • FileReader
    說明點:
  • 將day09下的hello.txt文件內(nèi)容讀入程序中,并輸出到控制臺

    • read()的理解:返回讀入的一個字符。如果達到文件末尾,返回-1
    • 異常的處理:為了保證流資源一定可以執(zhí)行關(guān)閉操作。需要使用try-catch-finally處理
    • 讀入的文件一定要存在,否則就會報FileNotFoundException。
    @Test public void testFileReader() {FileReader fr = null;try {//1. File類的實例化File file = new File("hello.txt"); // 相對于當(dāng)前module下//2. FileReader流的實例化fr = new FileReader(file);//3. 讀入操作 read()返回讀入的一個字符int data = fr.read(); // while (data != -1) { // System.out.print((char)data); // data = fr.read(); // }while ((data = fr.read()) != -1) {System.out.print((char) data);}} catch (IOException e) {e.printStackTrace();} finally {if (fr != null) { // 這里的判斷是因為如果 fr = new FileReader(file); 發(fā)生異常后,fr為null, 但還會執(zhí)行finally的內(nèi)容,此時fr.close();就會報空指針異常try {fr.close();} catch (IOException e) {e.printStackTrace();}}} }@Test public void testFileReader1() {FileReader fr = null;try {File file = new File("hello.txt");fr = new FileReader(file);char[] ch = new char[5];int len; // 每次讀入的字符個數(shù) read(char[] ch) // 一次讀取的字符個數(shù)為多少while ((len = fr.read(ch)) != -1) {// 方式一:// 錯誤寫法// for (int i = 0; i < ch.length; i++) {// System.out.print(ch[i]);// }// 正確寫法, 每次只取讀入的len(讀取的字符個數(shù))// for (int i = 0; i < len; i++) {// System.out.print(ch[i]);// }// 方式二:// 錯誤寫法// String str = new String(ch);// System.out.print(str);// 正確寫法, 每次只取讀入的len(讀取的字符個數(shù))String str = new String(ch, 0, len);System.out.print(str);}} catch (IOException e) {e.printStackTrace();} finally {if (fr != null) {try {fr.close();} catch (IOException e) {e.printStackTrace();}}} }
  • FileWriter
    從內(nèi)存中寫出數(shù)據(jù)到硬盤的文件里。
  • 說明:

    • 輸出操作,對應(yīng)的File可以不存在的。并不會報異常
    • File對應(yīng)的硬盤中的文件如果不存在,在輸出的過程中,會自動創(chuàng)建此文件。
      File對應(yīng)的硬盤中的文件如果存在:
      如果流使用的構(gòu)造器是:FileWriter(file,false) / FileWriter(file):對原文件的覆蓋
      如果流使用的構(gòu)造器是:FileWriter(file,true):不會對原文件覆蓋,而是在原文件基礎(chǔ)上追加內(nèi)容
    @Test public void testFileWriter() {FileWriter fw = null;try {//1.提供File類的對象,指明寫出到的文件File file = new File("hello1.txt");//2.提供FileWriter的對象,用于數(shù)據(jù)的寫出fw = new FileWriter(file,false);//3.寫出的操作fw.write("I have a dream!\n");fw.write("you need to have a dream!");} catch (IOException e) {e.printStackTrace();} finally {//4.流資源的關(guān)閉if(fw != null){try {fw.close();} catch (IOException e) {e.printStackTrace();}}} } 1.3 文本文件的復(fù)制: @Testpublic void testFileReaderFileWriter() {FileReader fr = null;FileWriter fw = null;try {//1.創(chuàng)建File類的對象,指明讀入和寫出的文件File srcFile = new File("hello.txt");File destFile = new File("hello2.txt");//不能使用字符流來處理圖片等字節(jié)數(shù)據(jù) // File srcFile = new File("愛情與友情.jpg"); // File destFile = new File("愛情與友情1.jpg");//2.創(chuàng)建輸入流和輸出流的對象fr = new FileReader(srcFile);fw = new FileWriter(destFile);//3.數(shù)據(jù)的讀入和寫出操作char[] cbuf = new char[5];int len;//記錄每次讀入到cbuf數(shù)組中的字符的個數(shù)while((len = fr.read(cbuf)) != -1){//每次寫出len個字符(正好是讀入的文件個數(shù))fw.write(cbuf,0,len);}} catch (IOException e) {e.printStackTrace();} finally {//4.關(guān)閉流資源//方式一: // try { // if(fw != null) // fw.close(); // } catch (IOException e) { // e.printStackTrace(); // }finally{ // try { // if(fr != null) // fr.close(); // } catch (IOException e) { // e.printStackTrace(); // } // }//方式二:try {if(fw != null)fw.close();} catch (IOException e) {e.printStackTrace();}try {if(fr != null)fr.close();} catch (IOException e) {e.printStackTrace();}}}2.FileInputStream / FileOutputStream的使用: * 1. 對于文本文件(.txt,.java,.c,.cpp),使用字符流處理 * 2. 對于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,...),使用字節(jié)流處理 /* 實現(xiàn)對圖片的復(fù)制操作*/ @Test public void testFileInputOutputStream() {FileInputStream fis = null;FileOutputStream fos = null;try {//1.造文件File srcFile = new File("愛情與友情.jpg");File destFile = new File("愛情與友情2.jpg");//2.造流fis = new FileInputStream(srcFile);fos = new FileOutputStream(destFile);//3.復(fù)制的過程byte[] buffer = new byte[5];int len;while((len = fis.read(buffer)) != -1){fos.write(buffer,0,len);}} catch (IOException e) {e.printStackTrace();} finally {if(fos != null){//4.關(guān)閉流try {fos.close();} catch (IOException e) {e.printStackTrace();}}if(fis != null){try {fis.close();} catch (IOException e) {e.printStackTrace();}}} }

    三、緩沖流

    1.緩沖流涉及到的類:* BufferedInputStream * BufferedOutputStream * BufferedReader * BufferedWriter2.作用: 作用:提供流的讀取、寫入的速度 提高讀寫速度的原因:內(nèi)部提供了一個緩沖區(qū)。默認情況下是8kb3.典型代碼 3.1 使用BufferedInputStream和BufferedOutputStream:處理非文本文件 //實現(xiàn)文件復(fù)制的方法public void copyFileWithBuffered(String srcPath,String destPath){BufferedInputStream bis = null;BufferedOutputStream bos = null;try {//1.造文件File srcFile = new File(srcPath);File destFile = new File(destPath);//2.造流//2.1 造節(jié)點流FileInputStream fis = new FileInputStream((srcFile));FileOutputStream fos = new FileOutputStream(destFile);//2.2 造緩沖流bis = new BufferedInputStream(fis);bos = new BufferedOutputStream(fos);//3.復(fù)制的細節(jié):讀取、寫入byte[] buffer = new byte[1024];int len;while((len = bis.read(buffer)) != -1){bos.write(buffer,0,len);}} catch (IOException e) {e.printStackTrace();} finally {//4.資源關(guān)閉//要求:先關(guān)閉外層的流,再關(guān)閉內(nèi)層的流if(bos != null){try {bos.close();} catch (IOException e) {e.printStackTrace();}}if(bis != null){try {bis.close();} catch (IOException e) {e.printStackTrace();}}//說明:關(guān)閉外層流的同時,內(nèi)層流也會自動的進行關(guān)閉。關(guān)于內(nèi)層流的關(guān)閉,我們可以省略. // fos.close(); // fis.close();}}3.2 使用BufferedReader和BufferedWriter:處理文本文件 @Testpublic void testBufferedReaderBufferedWriter(){BufferedReader br = null;BufferedWriter bw = null;try {//創(chuàng)建文件和相應(yīng)的流br = new BufferedReader(new FileReader(new File("dbcp.txt")));bw = new BufferedWriter(new FileWriter(new File("dbcp1.txt")));//讀寫操作//方式一:使用char[]數(shù)組 // char[] cbuf = new char[1024]; // int len; // while((len = br.read(cbuf)) != -1){ // bw.write(cbuf,0,len); // // bw.flush(); // }//方式二:使用StringString data;while((data = br.readLine()) != null){//方法一: // bw.write(data + "\n");//data中不包含換行符//方法二:bw.write(data);//data中不包含換行符bw.newLine();//提供換行的操作}} catch (IOException e) {e.printStackTrace();} finally {//關(guān)閉資源if(bw != null){try {bw.close();} catch (IOException e) {e.printStackTrace();}}if(br != null){try {br.close();} catch (IOException e) {e.printStackTrace();}}}}

    四、轉(zhuǎn)換流

  • 轉(zhuǎn)換流涉及到的類:屬于字符流
    • InputStreamReader:將一個字節(jié)的輸入流轉(zhuǎn)換為字符的輸入流
      解碼:字節(jié)、字節(jié)數(shù)組 —>字符數(shù)組、字符串

    • OutputStreamWriter:將一個字符的輸出流轉(zhuǎn)換為字節(jié)的輸出流
      編碼:字符數(shù)組、字符串 —> 字節(jié)、字節(jié)數(shù)組

    說明:編碼決定了解碼的方式

  • 作用:提供字節(jié)流與字符流之間的轉(zhuǎn)換

  • 圖示:

  • 典型實現(xiàn):

  • @Testpublic void test1() throws IOException {FileInputStream fis = new FileInputStream("dbcp.txt"); // InputStreamReader isr = new InputStreamReader(fis);//使用系統(tǒng)默認的字符集//參數(shù)2指明了字符集,具體使用哪個字符集,取決于文件dbcp.txt保存時使用的字符集InputStreamReader isr = new InputStreamReader(fis,"UTF-8");//使用系統(tǒng)默認的字符集char[] cbuf = new char[20];int len;while((len = isr.read(cbuf)) != -1){String str = new String(cbuf,0,len);System.out.print(str);}isr.close();}/* 此時處理異常的話,仍然應(yīng)該使用try-catch-finally綜合使用InputStreamReader和OutputStreamWriter*/ @Test public void test2() throws Exception {//1.造文件、造流File file1 = new File("dbcp.txt");File file2 = new File("dbcp_gbk.txt");FileInputStream fis = new FileInputStream(file1);FileOutputStream fos = new FileOutputStream(file2);InputStreamReader isr = new InputStreamReader(fis,"utf-8");OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk");//2.讀寫過程char[] cbuf = new char[20];int len;while((len = isr.read(cbuf)) != -1){osw.write(cbuf,0,len);}//3.關(guān)閉資源isr.close();osw.close();}

  • 說明:
    //文件編碼的方式(比如:GBK),決定了解析時使用的字符集(也只能是GBK)。
  • 五、標(biāo)準(zhǔn)輸入輸出流、打印流、數(shù)據(jù)流 ( 了解 )

    1. 標(biāo)準(zhǔn)的輸入輸出流: System.in:標(biāo)準(zhǔn)的輸入流,默認從鍵盤輸入 System.out:標(biāo)準(zhǔn)的輸出流,默認從控制臺輸出修改默認的輸入和輸出行為: System類的setIn(InputStream is) / setOut(PrintStream ps)方式重新指定輸入和輸出的流。2. 打印流: PrintStream 和PrintWriter 說明: 提供了一系列重載的print()println()方法,用于多種數(shù)據(jù)類型的輸出 System.out返回的是PrintStream的實例3. 數(shù)據(jù)流: DataInputStream 和 DataOutputStream 作用: 用于讀取或?qū)懗龌緮?shù)據(jù)類型的變量或字符串示例代碼: /* 練習(xí):將內(nèi)存中的字符串、基本數(shù)據(jù)類型的變量寫出到文件中。注意:處理異常的話,仍然應(yīng)該使用try-catch-finally.*/ @Test public void test3() throws IOException {//1.DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));//2.dos.writeUTF("劉建辰");dos.flush();//刷新操作,將內(nèi)存中的數(shù)據(jù)寫入文件dos.writeInt(23);dos.flush();dos.writeBoolean(true);dos.flush();//3.dos.close();} /* 將文件中存儲的基本數(shù)據(jù)類型變量和字符串讀取到內(nèi)存中,保存在變量中。注意點:讀取不同類型的數(shù)據(jù)的順序要與當(dāng)初寫入文件時,保存的數(shù)據(jù)的順序一致!*/ @Test public void test4() throws IOException {//1.DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));//2.String name = dis.readUTF();int age = dis.readInt();boolean isMale = dis.readBoolean();System.out.println("name = " + name);System.out.println("age = " + age);System.out.println("isMale = " + isMale);//3.dis.close();}

    六、對象流

  • 對象流:
    ObjectInputStream和 ObjectOutputStream
  • 作用:
    ObjectOutputStream:內(nèi)存中的對象—>存儲中的文件、通過網(wǎng)絡(luò)傳輸出去:序列化過程
    ObjectInputStream:存儲中的文件、通過網(wǎng)絡(luò)接收過來 —>內(nèi)存中的對象:反序列化過程
  • 對象的序列化機制:
    對象序列化機制允許把內(nèi)存中的Java對象轉(zhuǎn)換成平臺無關(guān)的二進制流,從而允許把這種二進制流持久地保存在磁盤
    上,或通過網(wǎng)絡(luò)將這種二進制流傳輸?shù)搅硪粋€網(wǎng)絡(luò)節(jié)點。//當(dāng)其它程序獲取了這種二進制流,就可以恢復(fù)成原來的Java對象
  • 序列化代碼實現(xiàn):
  • @Test public void testObjectOutputStream(){ObjectOutputStream oos = null;try {//1.oos = new ObjectOutputStream(new FileOutputStream("object.dat"));//2.oos.writeObject(new String("我愛北京天安門"));oos.flush();//刷新操作oos.writeObject(new Person("王銘",23));oos.flush();oos.writeObject(new Person("張學(xué)良",23,1001,new Account(5000)));oos.flush();} catch (IOException e) {e.printStackTrace();} finally {if(oos != null){//3.try {oos.close();} catch (IOException e) {e.printStackTrace();}}}}
  • 反序列化代碼實現(xiàn):
  • @Test public void testObjectInputStream(){ObjectInputStream ois = null;try {ois = new ObjectInputStream(new FileInputStream("object.dat"));Object obj = ois.readObject();String str = (String) obj;Person p = (Person) ois.readObject();Person p1 = (Person) ois.readObject();System.out.println(str);System.out.println(p);System.out.println(p1);} catch (IOException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();} finally {if(ois != null){try {ois.close();} catch (IOException e) {e.printStackTrace();}}} }
  • 實現(xiàn)序列化的對象所屬的類需要滿足:
    • 1.需要實現(xiàn)接口:Serializable

    • 2.當(dāng)前類提供一個全局常量:serialVersionUID

    • 3.除了當(dāng)前Person類需要實現(xiàn)Serializable接口之外,還必須保證其內(nèi)部所屬性

    • 也必須是可序列化的。(默認情況下,基本數(shù)據(jù)類型可序列化)

    • 補充:ObjectOutputStream和ObjectInputStream不能序列化

    • static和transient修飾的成員變量

    • transient來修飾某個成員不被序列化!

    總結(jié)

    以上是生活随笔為你收集整理的IO流——流的分类、InputStream、OutputStream、Reader、Writer等的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。