1. 程式人生 > 其它 >位元組緩衝流&字元流

位元組緩衝流&字元流

1.位元組緩衝流

1.1位元組緩衝流構造方法【應用】

  • 位元組緩衝流介紹

    • lBufferOutputStream:該類實現緩衝輸出流。 通過設定這樣的輸出流,應用程式可以向底層輸出流寫入位元組,而不必為寫入的每個位元組導致底層系統的呼叫

    • lBufferedInputStream:建立BufferedInputStream將建立一個內部緩衝區陣列。 當從流中讀取或跳過位元組時,內部緩衝區將根據需要從所包含的輸入流中重新填充,一次很多位元組

  • 構造方法:

    方法名 說明
    BufferedOutputStream(OutputStream out) 建立位元組緩衝輸出流物件
    BufferedInputStream(InputStream in) 建立位元組緩衝輸入流物件
  • 示例程式碼

    public class BufferStreamDemo {
        public static void main(String[] args) throws IOException {
            //位元組緩衝輸出流:BufferedOutputStream(OutputStream out)
     
            BufferedOutputStream bos = new BufferedOutputStream(new 				                                       FileOutputStream("myByteStream\\bos.txt"));
            //寫資料
            bos.write("hello\r\n".getBytes());
            bos.write("world\r\n".getBytes());
            //釋放資源
            bos.close();
        
    
            //位元組緩衝輸入流:BufferedInputStream(InputStream in)
            BufferedInputStream bis = new BufferedInputStream(new                                                          FileInputStream("myByteStream\\bos.txt"));
    
            //一次讀取一個位元組資料
    //        int by;
    //        while ((by=bis.read())!=-1) {
    //            System.out.print((char)by);
    //        }
    
            //一次讀取一個位元組陣列資料
            byte[] bys = new byte[1024];
            int len;
            while ((len=bis.read(bys))!=-1) {
                System.out.print(new String(bys,0,len));
            }
    
            //釋放資源
            bis.close();
        }
    }
    

1.2位元組流複製視訊【應用】

  • 案例需求

    把“E:\itcast\位元組流複製圖片.avi”複製到模組目錄下的“位元組流複製圖片.avi”

  • 實現步驟

    • 根據資料來源建立位元組輸入流物件

    • 根據目的地建立位元組輸出流物件

    • 讀寫資料,複製視訊

    • 釋放資源

  • 程式碼實現

    public class CopyAviDemo {
        public static void main(String[] args) throws IOException {
            //記錄開始時間
            long startTime = System.currentTimeMillis();
    
            //複製視訊
    //        method1();
    //        method2();
    //        method3();
            method4();
    
            //記錄結束時間
            long endTime = System.currentTimeMillis();
            System.out.println("共耗時:" + (endTime - startTime) + "毫秒");
        }
    
        //位元組緩衝流一次讀寫一個位元組陣列
        public static void method4() throws IOException {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\itcast\\位元組流複製圖片.avi"));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("myByteStream\\位元組流複製圖片.avi"));
    
            byte[] bys = new byte[1024];
            int len;
            while ((len=bis.read(bys))!=-1) {
                bos.write(bys,0,len);
            }
    
            bos.close();
            bis.close();
        }
    
        //位元組緩衝流一次讀寫一個位元組
        public static void method3() throws IOException {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream("E:\\itcast\\位元組流複製圖片.avi"));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("myByteStream\\位元組流複製圖片.avi"));
    
            int by;
            while ((by=bis.read())!=-1) {
                bos.write(by);
            }
    
            bos.close();
            bis.close();
        }
    
    
        //基本位元組流一次讀寫一個位元組陣列
        public static void method2() throws IOException {
            //E:\\itcast\\位元組流複製圖片.avi
            //模組目錄下的 位元組流複製圖片.avi
            FileInputStream fis = new FileInputStream("E:\\itcast\\位元組流複製圖片.avi");
            FileOutputStream fos = new FileOutputStream("myByteStream\\位元組流複製圖片.avi");
    
            byte[] bys = new byte[1024];
            int len;
            while ((len=fis.read(bys))!=-1) {
                fos.write(bys,0,len);
            }
    
            fos.close();
            fis.close();
        }
    
        //基本位元組流一次讀寫一個位元組
        public static void method1() throws IOException {
            //E:\\itcast\\位元組流複製圖片.avi
            //模組目錄下的 位元組流複製圖片.avi
            FileInputStream fis = new FileInputStream("E:\\itcast\\位元組流複製圖片.avi");
            FileOutputStream fos = new FileOutputStream("myByteStream\\位元組流複製圖片.avi");
    
            int by;
            while ((by=fis.read())!=-1) {
                fos.write(by);
            }
    
            fos.close();
            fis.close();
        }
    }
    

2.字元流

2.1為什麼會出現字元流【理解】

  • 字元流的介紹

    由於位元組流操作中文不是特別的方便,所以Java就提供字元流

    字元流 = 位元組流 + 編碼表

  • 中文的位元組儲存方式

    用位元組流複製文字檔案時,文字檔案也會有中文,但是沒有問題,原因是最終底層操作會自動進行位元組拼接成中文,如何識別是中文的呢?

    漢字在儲存的時候,無論選擇哪種編碼儲存,第一個位元組都是負數

2.2編碼表【理解】

  • 什麼是字符集

    是一個系統支援的所有字元的集合,包括各國家文字、標點符號、圖形符號、數字等

    l計算機要準確的儲存和識別各種字符集符號,就需要進行字元編碼,一套字符集必然至少有一套字元編碼。常見字符集有ASCII字符集、GBXXX字符集、Unicode字符集等

  • 常見的字符集

    • ASCII字符集:

      lASCII:是基於拉丁字母的一套電腦編碼系統,用於顯示現代英語,主要包括控制字元(回車鍵、退格、換行鍵等)和可顯示字元(英文大小寫字元、阿拉伯數字和西文符號)

      基本的ASCII字符集,使用7位表示一個字元,共128字元。ASCII的擴充套件字符集使用8位表示一個字元,共256字元,方便支援歐洲常用字元。是一個系統支援的所有字元的集合,包括各國家文字、標點符號、圖形符號、數字等

    • GBXXX字符集:

      GBK:最常用的中文碼錶。是在GB2312標準基礎上的擴充套件規範,使用了雙位元組編碼方案,共收錄了21003個漢字,完全相容GB2312標準,同時支援繁體漢字以及日韓漢字等

    • Unicode字符集:

      UTF-8編碼:可以用來表示Unicode標準中任意字元,它是電子郵件、網頁及其他儲存或傳送文字的應用 中,優先採用的編碼。網際網路工程工作小組(IETF)要求所有網際網路協議都必須支援UTF-8編碼。它使用一至四個位元組為每個字元編碼

      編碼規則:

      128個US-ASCII字元,只需一個位元組編碼

      拉丁文等字元,需要二個位元組編碼

      大部分常用字(含中文),使用三個位元組編碼

      其他極少使用的Unicode輔助字元,使用四位元組編碼

2.3字串中的編碼解碼問題【應用】

  • 相關方法

    方法名 說明
    byte[] getBytes() 使用平臺的預設字符集將該 String編碼為一系列位元組
    byte[] getBytes(String charsetName) 使用指定的字符集將該 String編碼為一系列位元組
    String(byte[] bytes) 使用平臺的預設字符集解碼指定的位元組陣列來建立字串
    String(byte[] bytes, String charsetName) 通過指定的字符集解碼指定的位元組陣列來建立字串
  • 程式碼演示

    public class StringDemo {
        public static void main(String[] args) throws UnsupportedEncodingException {
            //定義一個字串
            String s = "中國";
    
            //byte[] bys = s.getBytes(); //[-28, -72, -83, -27, -101, -67]
            //byte[] bys = s.getBytes("UTF-8"); //[-28, -72, -83, -27, -101, -67]
            byte[] bys = s.getBytes("GBK"); //[-42, -48, -71, -6]
            System.out.println(Arrays.toString(bys));
    
            //String ss = new String(bys);
            //String ss = new String(bys,"UTF-8");
            String ss = new String(bys,"GBK");
            System.out.println(ss);
        }
    }
    

2.4字元流中的編碼解碼問題【應用】

  • 字元流中和編碼解碼問題相關的兩個類

    • InputStreamReader:是從位元組流到字元流的橋樑

      ​ 它讀取位元組,並使用指定的編碼將其解碼為字元

      ​ 它使用的字符集可以由名稱指定,也可以被明確指定,或者可以接受平臺的預設字符集

    • OutputStreamWriter:是從字元流到位元組流的橋樑

      ​ 是從字元流到位元組流的橋樑,使用指定的編碼將寫入的字元編碼為位元組

      ​ 它使用的字符集可以由名稱指定,也可以被明確指定,或者可以接受平臺的預設字符集

  • 構造方法

    方法名 說明
    InputStreamReader(InputStream in) 使用預設字元編碼建立InputStreamReader物件
    InputStreamReader(InputStream in,String chatset) 使用指定的字元編碼建立InputStreamReader物件
    OutputStreamWriter(OutputStream out) 使用預設字元編碼建立OutputStreamWriter物件
    OutputStreamWriter(OutputStream out,String charset) 使用指定的字元編碼建立OutputStreamWriter物件
  • 程式碼演示

    public class ConversionStreamDemo {
        public static void main(String[] args) throws IOException {
            //OutputStreamWriter osw = new OutputStreamWriter(new                                             FileOutputStream("myCharStream\\osw.txt"));
            OutputStreamWriter osw = new OutputStreamWriter(new                                              FileOutputStream("myCharStream\\osw.txt"),"GBK");
            osw.write("中國");
            osw.close();
    
            //InputStreamReader isr = new InputStreamReader(new 	                                         FileInputStream("myCharStream\\osw.txt"));
            InputStreamReader isr = new InputStreamReader(new                                                 FileInputStream("myCharStream\\osw.txt"),"GBK");
            //一次讀取一個字元資料
            int ch;
            while ((ch=isr.read())!=-1) {
                System.out.print((char)ch);
            }
            isr.close();
        }
    }
    

2.5字元流寫資料的5種方式【應用】

  • 方法介紹

    方法名 說明
    void write(int c) 寫一個字元
    void write(char[] cbuf) 寫入一個字元陣列
    void write(char[] cbuf, int off, int len) 寫入字元陣列的一部分
    void write(String str) 寫一個字串
    void write(String str, int off, int len) 寫一個字串的一部分
  • 重新整理和關閉的方法

    方法名 說明
    flush() 重新整理流,之後還可以繼續寫資料
    close() 關閉流,釋放資源,但是在關閉之前會先重新整理流。一旦關閉,就不能再寫資料
  • 程式碼演示

    public class OutputStreamWriterDemo {
        public static void main(String[] args) throws IOException {
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("myCharStream\\osw.txt"));
    
            //void write(int c):寫一個字元
    //        osw.write(97);
    //        osw.write(98);
    //        osw.write(99);
    
            //void writ(char[] cbuf):寫入一個字元陣列
            char[] chs = {'a', 'b', 'c', 'd', 'e'};
    //        osw.write(chs);
    
            //void write(char[] cbuf, int off, int len):寫入字元陣列的一部分
    //        osw.write(chs, 0, chs.length);
    //        osw.write(chs, 1, 3);
    
            //void write(String str):寫一個字串
    //        osw.write("abcde");
    
            //void write(String str, int off, int len):寫一個字串的一部分
    //        osw.write("abcde", 0, "abcde".length());
            osw.write("abcde", 1, 3);
    
            //釋放資源
            osw.close();
        }
    }
    

2.6字元流讀資料的2種方式【應用】

  • 方法介紹

    方法名 說明
    int read() 一次讀一個字元資料
    int read(char[] cbuf) 一次讀一個字元陣列資料
  • 程式碼演示

    public class InputStreamReaderDemo {
        public static void main(String[] args) throws IOException {
       
            InputStreamReader isr = new InputStreamReader(new FileInputStream("myCharStream\\ConversionStreamDemo.java"));
    
            //int read():一次讀一個字元資料
    //        int ch;
    //        while ((ch=isr.read())!=-1) {
    //            System.out.print((char)ch);
    //        }
    
            //int read(char[] cbuf):一次讀一個字元陣列資料
            char[] chs = new char[1024];
            int len;
            while ((len = isr.read(chs)) != -1) {
                System.out.print(new String(chs, 0, len));
            }
    
            //釋放資源
            isr.close();
        }
    }
    

2.7字元流複製Java檔案【應用】

  • 案例需求

    把模組目錄下的“ConversionStreamDemo.java” 複製到模組目錄下的“Copy.java”

  • 實現步驟

    • 根據資料來源建立字元輸入流物件
    • 根據目的地建立字元輸出流物件
    • 讀寫資料,複製檔案
    • 釋放資源
  • 程式碼實現

    public class CopyJavaDemo01 {
        public static void main(String[] args) throws IOException {
            //根據資料來源建立字元輸入流物件
            InputStreamReader isr = new InputStreamReader(new FileInputStream("myCharStream\\ConversionStreamDemo.java"));
            //根據目的地建立字元輸出流物件
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("myCharStream\\Copy.java"));
    
            //讀寫資料,複製檔案
            //一次讀寫一個字元資料
    //        int ch;
    //        while ((ch=isr.read())!=-1) {
    //            osw.write(ch);
    //        }
    
            //一次讀寫一個字元陣列資料
            char[] chs = new char[1024];
            int len;
            while ((len=isr.read(chs))!=-1) {
                osw.write(chs,0,len);
            }
    
            //釋放資源
            osw.close();
            isr.close();
        }
    }
    

2.8字元流複製Java檔案改進版【應用】

  • 案例需求

    使用便捷流物件,把模組目錄下的“ConversionStreamDemo.java” 複製到模組目錄下的“Copy.java”

  • 實現步驟

    • 根據資料來源建立字元輸入流物件

    • 根據目的地建立字元輸出流物件

    • 讀寫資料,複製檔案

    • 釋放資源

  • 程式碼實現

    public class CopyJavaDemo02 {
        public static void main(String[] args) throws IOException {
            //根據資料來源建立字元輸入流物件
            FileReader fr = new FileReader("myCharStream\\ConversionStreamDemo.java");
            //根據目的地建立字元輸出流物件
            FileWriter fw = new FileWriter("myCharStream\\Copy.java");
    
            //讀寫資料,複製檔案
    //        int ch;
    //        while ((ch=fr.read())!=-1) {
    //            fw.write(ch);
    //        }
    
            char[] chs = new char[1024];
            int len;
            while ((len=fr.read(chs))!=-1) {
                fw.write(chs,0,len);
            }
    
            //釋放資源
            fw.close();
            fr.close();
        }
    }
    

2.9字元緩衝流【應用】

  • 字元緩衝流介紹

    • BufferedWriter:將文字寫入字元輸出流,緩衝字元,以提供單個字元,陣列和字串的高效寫入,可以指定緩衝區大小,或者可以接受預設大小。預設值足夠大,可用於大多數用途

    • BufferedReader:從字元輸入流讀取文字,緩衝字元,以提供字元,陣列和行的高效讀取,可以指定緩衝區大小,或者可以使用預設大小。 預設值足夠大,可用於大多數用途

  • 構造方法

    方法名 說明
    BufferedWriter(Writer out) 建立字元緩衝輸出流物件
    BufferedReader(Reader in) 建立字元緩衝輸入流物件
  • 程式碼演示

    public class BufferedStreamDemo01 {
        public static void main(String[] args) throws IOException {
            //BufferedWriter(Writer out)
            BufferedWriter bw = new BufferedWriter(new                                                            FileWriter("myCharStream\\bw.txt"));
            bw.write("hello\r\n");
            bw.write("world\r\n");
            bw.close();
    
            //BufferedReader(Reader in)
            BufferedReader br = new BufferedReader(new                                                           FileReader("myCharStream\\bw.txt"));
    
            //一次讀取一個字元資料
    //        int ch;
    //        while ((ch=br.read())!=-1) {
    //            System.out.print((char)ch);
    //        }
    
            //一次讀取一個字元陣列資料
            char[] chs = new char[1024];
            int len;
            while ((len=br.read(chs))!=-1) {
                System.out.print(new String(chs,0,len));
            }
    
            br.close();
        }
    }
    

2.10字元緩衝流複製Java檔案【應用】

  • 案例需求

    把模組目錄下的ConversionStreamDemo.java 複製到模組目錄下的 Copy.java

  • 實現步驟

    • 根據資料來源建立字元緩衝輸入流物件
    • 根據目的地建立字元緩衝輸出流物件
    • 讀寫資料,複製檔案,使用字元緩衝流特有功能實現
    • 釋放資源
  • 程式碼實現

    public class CopyJavaDemo01 {
        public static void main(String[] args) throws IOException {
            //根據資料來源建立字元緩衝輸入流物件
            BufferedReader br = new BufferedReader(new FileReader("myCharStream\\ConversionStreamDemo.java"));
            //根據目的地建立字元緩衝輸出流物件
            BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\Copy.java"));
    
            //讀寫資料,複製檔案
            //一次讀寫一個字元資料
    //        int ch;
    //        while ((ch=br.read())!=-1) {
    //            bw.write(ch);
    //        }
    
            //一次讀寫一個字元陣列資料
            char[] chs = new char[1024];
            int len;
            while ((len=br.read(chs))!=-1) {
                bw.write(chs,0,len);
            }
    
            //釋放資源
            bw.close();
            br.close();
        }
    }
    

2.11字元緩衝流特有功能【應用】

  • 方法介紹

    BufferedWriter:

    方法名 說明
    void newLine() 寫一行行分隔符,行分隔符字串由系統屬性定義

    BufferedReader:

    方法名 說明
    String readLine() 讀一行文字。 結果包含行的內容的字串,不包括任何行終止字元如果流的結尾已經到達,則為null
  • 程式碼演示

    public class BufferedStreamDemo02 {
        public static void main(String[] args) throws IOException {
    
            //建立字元緩衝輸出流
            BufferedWriter bw = new BufferedWriter(new                                                          FileWriter("myCharStream\\bw.txt"));
    
            //寫資料
            for (int i = 0; i < 10; i++) {
                bw.write("hello" + i);
                //bw.write("\r\n");
                bw.newLine();
                bw.flush();
            }
    
            //釋放資源
            bw.close();
    
            //建立字元緩衝輸入流
            BufferedReader br = new BufferedReader(new                                                          FileReader("myCharStream\\bw.txt"));
    
            String line;
            while ((line=br.readLine())!=null) {
                System.out.println(line);
            }
    
            br.close();
        }
    }
    

2.12字元緩衝流特有功能複製Java檔案【應用】

  • 案例需求

    使用特有功能把模組目錄下的ConversionStreamDemo.java 複製到模組目錄下的 Copy.java

  • 實現步驟

    • 根據資料來源建立字元緩衝輸入流物件
    • 根據目的地建立字元緩衝輸出流物件
    • 讀寫資料,複製檔案,使用字元緩衝流特有功能實現
    • 釋放資源
  • 程式碼實現

    public class CopyJavaDemo02 {
        public static void main(String[] args) throws IOException {
            //根據資料來源建立字元緩衝輸入流物件
            BufferedReader br = new BufferedReader(new FileReader("myCharStream\\ConversionStreamDemo.java"));
            //根據目的地建立字元緩衝輸出流物件
            BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\Copy.java"));
    
            //讀寫資料,複製檔案
            //使用字元緩衝流特有功能實現
            String line;
            while ((line=br.readLine())!=null) {
                bw.write(line);
                bw.newLine();
                bw.flush();
            }
    
            //釋放資源
            bw.close();
            br.close();
        }
    }
    

2.13IO流小結【理解】

  • 位元組流
  • 字元流

3練習案例

3.1集合到檔案【應用】

  • 案例需求

    把文字檔案中的資料讀取到集合中,並遍歷集合。要求:檔案中每一行資料是一個集合元素

  • 實現步驟

    • 建立字元緩衝輸入流物件
    • 建立ArrayList集合物件
    • 呼叫字元緩衝輸入流物件的方法讀資料
    • 把讀取到的字串資料儲存到集合中
    • 釋放資源
    • 遍歷集合
  • 程式碼實現

    public class TxtToArrayListDemo {
        public static void main(String[] args) throws IOException {
            //建立字元緩衝輸入流物件
            BufferedReader br = new BufferedReader(new FileReader("myCharStream\\array.txt"));
    
            //建立ArrayList集合物件
            ArrayList<String> array = new ArrayList<String>();
    
            //呼叫字元緩衝輸入流物件的方法讀資料
            String line;
            while ((line=br.readLine())!=null) {
                //把讀取到的字串資料儲存到集合中
                array.add(line);
            }
            //釋放資源
            br.close();
            //遍歷集合
            for(String s : array) {
                System.out.println(s);
            }
        }
    }
    

3.2檔案到集合【應用】

  • 案例需求

    把ArrayList集合中的字串資料寫入到文字檔案。要求:每一個字串元素作為檔案中的一行資料

  • 實現步驟

    • 建立ArrayList集合
    • 往集合中儲存字串元素
    • 建立字元緩衝輸出流物件
    • 遍歷集合,得到每一個字串資料
    • 呼叫字元緩衝輸出流物件的方法寫資料
    • 釋放資源
  • 程式碼實現

    public class ArrayListToTxtDemo {
        public static void main(String[] args) throws IOException {
            //建立ArrayList集合
            ArrayList<String> array = new ArrayList<String>();
    
            //往集合中儲存字串元素
            array.add("hello");
            array.add("world");
            array.add("java");
    
            //建立字元緩衝輸出流物件
            BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\array.txt"));
    
            //遍歷集合,得到每一個字串資料
            for(String s : array) {
                //呼叫字元緩衝輸出流物件的方法寫資料
                bw.write(s);
                bw.newLine();
                bw.flush();
            }
    
            //釋放資源
            bw.close();
        }
    }
    

3.3點名器【應用】

  • 案例需求

    我有一個檔案裡面儲存了班級同學的姓名,每一個姓名佔一行,要求通過程式實現隨點名器

  • 實現步驟

    • 建立字元緩衝輸入流物件
    • 建立ArrayList集合物件
    • 呼叫字元緩衝輸入流物件的方法讀資料
    • 把讀取到的字串資料儲存到集合中
    • 釋放資源
    • 使用Random產生一個隨機數,隨機數的範圍在:[0,集合的長度)
    • 把第6步產生的隨機數作為索引到ArrayList集合中獲取值
    • 把第7步得到的資料輸出在控制檯
  • 程式碼實現

    public class CallNameDemo {
        public static void main(String[] args) throws IOException {
            //建立字元緩衝輸入流物件
            BufferedReader br = new BufferedReader(new FileReader("myCharStream\\names.txt"));
    
            //建立ArrayList集合物件
            ArrayList<String> array = new ArrayList<String>();
    
            //呼叫字元緩衝輸入流物件的方法讀資料
            String line;
            while ((line=br.readLine())!=null) {
                //把讀取到的字串資料儲存到集合中
                array.add(line);
            }
    
            //釋放資源
            br.close();
    
            //使用Random產生一個隨機數,隨機數的範圍在:[0,集合的長度)
            Random r = new Random();
            int index = r.nextInt(array.size());
    
            //把第6步產生的隨機數作為索引到ArrayList集合中獲取值
            String name = array.get(index);
    
            //把第7步得到的資料輸出在控制檯
            System.out.println("幸運者是:" + name);
        }
    }
    

3.4集合到檔案改進版【應用】

  • 案例需求

    把ArrayList集合中的學生資料寫入到文字檔案。要求:每一個學生物件的資料作為檔案中的一行資料
    ​ 格式:學號,姓名,年齡,居住地 舉例:itheima001,林青霞,30,西安

  • 實現步驟

    • 定義學生類
    • 建立ArrayList集合
    • 建立學生物件
    • 把學生物件新增到集合中
    • 建立字元緩衝輸出流物件
    • 遍歷集合,得到每一個學生物件
    • 把學生物件的資料拼接成指定格式的字串
    • 呼叫字元緩衝輸出流物件的方法寫資料
    • 釋放資源
  • 程式碼實現

    • 學生類

      public class Student {
          private String sid;
          private String name;
          private int age;
          private String address;
      
          public Student() {
          }
      
          public Student(String sid, String name, int age, String address) {
              this.sid = sid;
              this.name = name;
              this.age = age;
              this.address = address;
          }
      
          public String getSid() {
              return sid;
          }
      
          public void setSid(String sid) {
              this.sid = sid;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      
          public String getAddress() {
              return address;
          }
      
          public void setAddress(String address) {
              this.address = address;
          }
      }
      
    • 測試類

      public class ArrayListToFileDemo {
          public static void main(String[] args) throws IOException {
              //建立ArrayList集合
              ArrayList<Student> array = new ArrayList<Student>();
      
              //建立學生物件
              Student s1 = new Student("itheima001", "林青霞", 30, "西安");
              Student s2 = new Student("itheima002", "張曼玉", 35, "武漢");
              Student s3 = new Student("itheima003", "王祖賢", 33, "鄭州");
      
              //把學生物件新增到集合中
              array.add(s1);
              array.add(s2);
              array.add(s3);
      
              //建立字元緩衝輸出流物件
              BufferedWriter bw = new BufferedWriter(new FileWriter("myCharStream\\students.txt"));
      
              //遍歷集合,得到每一個學生物件
              for (Student s : array) {
                  //把學生物件的資料拼接成指定格式的字串
                  StringBuilder sb = new StringBuilder();
                  sb.append(s.getSid()).append(",").append(s.getName()).append(",").append(s.getAge()).append(",").append(s.getAddress());
      
                  //呼叫字元緩衝輸出流物件的方法寫資料
                  bw.write(sb.toString());
                  bw.newLine();
                  bw.flush();
              }
      
              //釋放資源
              bw.close();
          }
      }
      

3.5檔案到集合改進版【應用】

  • 案例需求

    把文字檔案中的資料讀取到集合中,並遍歷集合。要求:檔案中每一行資料是一個學生物件的成員變數值
    舉例:itheima001,林青霞,30,西安

  • 實現步驟

    • 定義學生類
    • 建立字元緩衝輸入流物件
    • 建立ArrayList集合物件
    • 呼叫字元緩衝輸入流物件的方法讀資料
    • 把讀取到的字串資料用split()進行分割,得到一個字串陣列
    • 建立學生物件
    • 把字串陣列中的每一個元素取出來對應的賦值給學生物件的成員變數值
    • 把學生物件新增到集合
    • 釋放資源
    • 遍歷集合
  • 程式碼實現

    • 學生類

      ​ 同上

    • 測試類

      public class FileToArrayListDemo {
          public static void main(String[] args) throws IOException {
              //建立字元緩衝輸入流物件
              BufferedReader br = new BufferedReader(new FileReader("myCharStream\\students.txt"));
      
              //建立ArrayList集合物件
              ArrayList<Student> array = new ArrayList<Student>();
      
              //呼叫字元緩衝輸入流物件的方法讀資料
              String line;
              while ((line = br.readLine()) != null) {
                  //把讀取到的字串資料用split()進行分割,得到一個字串陣列
                  String[] strArray = line.split(",");
      
                  //建立學生物件
                  Student s = new Student();
                  //把字串陣列中的每一個元素取出來對應的賦值給學生物件的成員變數值
                  //itheima001,林青霞,30,西安
                  s.setSid(strArray[0]);
                  s.setName(strArray[1]);
                  s.setAge(Integer.parseInt(strArray[2]));
                  s.setAddress(strArray[3]);
      
                  //把學生物件新增到集合
                  array.add(s);
              }
      
              //釋放資源
              br.close();
      
              //遍歷集合
              for (Student s : array) {
                  System.out.println(s.getSid() + "," + s.getName() + "," + s.getAge() + "," + s.getAddress());
              }
          }
      }