天天看點

java基礎學習_IO流03_字元流、IO流小結、案例_day21總結

java基礎學習_IO流03_字元流、IO流小結、案例_day21總結

=============================================================================
=============================================================================
涉及到的知識點有:
    1:字元流(掌握)
        (1)轉換流出現的原因及作用
        (2)轉換流其實是一個字元流。
        (3)編碼表
            A:編碼表的概述
            B:常見的編碼表
            C:字元串中的編碼問題
        (4)IO流中的編碼問題
        (5)字元轉換流的5種寫資料的方式
        (6)字元轉換流的2種讀資料的方式
        (7)面試題
        (8)字元轉換流(= 字元流 = 轉換流) ==> 字元轉換簡化流 ==> 字元流
        (9)字元緩沖區流
        (10)字元流
    2:IO流小結(掌握)
    3:案例(掌握)
        A:複制文本檔案(用字元流) 5種方式(掌握)
        B:複制圖檔/視訊/音頻(用位元組流) 4種方式(掌握)
        C:把ArrayList集合中的資料存儲到文本檔案
        D:從文本檔案中讀取資料(每一行為一個字元串資料)到ArrayList集合中,并周遊集合
        E:我有一個文本檔案中存儲了幾個名字,請大家寫一個程式實作随機擷取一個人的名字。
        F:複制指定單級檔案夾中的所有檔案(裡面隻有檔案,且檔案各種各樣)
        G:複制指定單級檔案夾中的指定的檔案,并修改檔案字尾名(裡面隻有檔案,且檔案各種各樣,但是本例題為了增加一點難度,使該單級檔案夾中增加一個檔案夾名為hello.java的檔案夾)
        H:複制多級檔案夾
        I:鍵盤錄入5個學生資訊(姓名,國文成績,數學成績,英語成績),按照總分從高到低存入文本檔案。
        J:已知在s.txt檔案中有這樣的一個字元串:“hcexfgijkamdnoqrzstuvwybpl”,請編寫程式讀取s.txt檔案的資料内容,把讀取到的資料排序後寫入到ss.txt中。
        K:用Reader來模拟BufferedReader的特有功能readLine()
        L:用自定義類來模拟LineNumberReader的特有功能getLineNumber()和setLineNumber()
=============================================================================
=============================================================================
1:字元流(掌握)
    (1)轉換流出現的原因及作用
        轉換流出現的原因:位元組流操作中文資料不是特别的友善,是以,java就提供了轉換流。
        轉換流的作用:就是把位元組流轉換字元流來使用。
    (2)轉換流其實是一個字元流。
        字元流 = 位元組流 + 編碼表
---------------------------------------
    (3)編碼表
        A:編碼表的概述
            就是由現實世界的字元和對應的數值組成的一張表。
        B:常見的編碼表
            ASCII:美國标準資訊交換碼。
                用一個位元組的7位表示(最高位為符号位,其餘位為數值位)。
            Unicode:國際标準碼,融合了多種文字。
                所有文字都用兩個位元組來表示,Java語言使用的就是Unicode編碼。
            ISO-8859-1:拉丁碼表。歐洲碼表。
                用一個位元組的8位表示。
            GB2312:中國的中文編碼表。(簡體中文)
            GBK:中國的中文編碼表更新,融合了更多的中文文字元号。(簡體中文)
            GB18030:GBK的取代版本。(簡體中文)
            BIG5:通用于台灣、香港地區的一個繁體字編碼方案,俗稱“大五碼”。
            UTF-8:最多用三個位元組來表示一個字元。
                UTF-8不同,它定義了一種“區間規則”,這種規則可以和ASCII編碼保持最大程度的相容:
                它将Unicode編碼為 00000000-0000007F 的字元,用單個位元組來表示;
                它将Unicode編碼為 00000080-000007FF 的字元,用兩個位元組表示;
                它将Unicode編碼為 00000800-0000FFFF 的字元,用三個位元組表示。
C:字元串中的編碼問題
            String類的構造方法:
                public String(byte[] bytes, String charsetName) 通過指定的字元集解碼位元組數組
            String類的成員方法:
                public byte[] getBytes(String charsetName) 使用指定的字元集合把字元串編碼為位元組數組
            
            編碼:把看得懂的變成看不懂的
                String --> byte[]
            解碼:把看不懂的變成看得懂的
                byte[] --> String
      
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_01;
 2 
 3 import java.io.UnsupportedEncodingException;
 4 import java.util.Arrays;
 5 
 6 /*
 7  * String類的構造方法:
 8  *         public String(byte[] bytes, String charsetName) 通過指定的字元集解碼位元組數組
 9  * String類的成員方法:
10  *         public byte[] getBytes(String charsetName) 使用指定的字元集合把字元串編碼為位元組數組
11  * 
12  * 編碼:把看得懂的變成看不懂的
13  *         String --> byte[]
14  * 
15  * 解碼:把看不懂的變成看得懂的
16  *         byte[] --> String
17  * 
18  * 舉例:諜戰片(發電報,接電報)
19  * 
20  * 碼表:密碼本
21  *         字元 <--> 數值
22  * 
23  * 要發送一段文字:
24  *         今天晚上在老地方見
25  * 
26  *         發送端:今 --> 字元 --> 數值 --> 十進制 --> 二進制 --> 發送
27  *         接收端:接收 --> 二進制 --> 十進制 --> 數值 --> 字元 --> 今
28  * 
29  *         今天晚上在老地方見
30  * 
31  * 編碼問題簡單,隻要編碼解碼的格式是一緻的就沒有問題。
32  */
33 public class StringDemo {
34     public static void main(String[] args) throws UnsupportedEncodingException {
35         // 本windows電腦預設的編碼是GBK
36         // 本Eclipse軟體預設的編碼是UTF-8
37         
38         String s = "你好";
39 
40         // 使用指定的字元集合把字元串編碼為位元組數組
41         // String --> byte[]
42         byte[] bys = s.getBytes(); // [-28, -67, -96, -27, -91, -67] 
43         // byte[] bys = s.getBytes("GBK"); // [-60, -29, -70, -61]
44         // byte[] bys = s.getBytes("UTF-8"); // [-28, -67, -96, -27, -91, -67]
45         System.out.println(Arrays.toString(bys)); // [-28, -67, -96, -27, -91, -67]
46 
47         // 通過指定的字元集解碼位元組數組
48         // byte[] --> String
49         String ss = new String(bys); // 你好
50         // String ss = new String(bys, "GBK"); // 浣犲ソ
51         // String ss = new String(bys, "UTF-8"); // 你好
52         System.out.println(ss); // 你好
53     }
54 }      

StringDemo.java

---------------------------------------
    (4)IO流中的編碼問題
        A:OutputStreamWriter字元轉換輸出流
            public OutputStreamWriter(OutputStream os) 預設編碼
            public OutputStreamWriter(OutputStream os, String charsetName) 指定編碼
        B:InputStreamReader字元轉換輸入流
            public InputStreamReader(InputStream is) 預設編碼
            public InputStreamReader(InputStream is, String charsetName) 指定編碼
        C:編碼問題其實很簡單
            編碼解碼隻要一緻即可。
---------------------------------------
    (5)字元轉換流的5種寫資料的方式
        OutputStreamWriter類的成員方法:
            public void write(int c) 寫一個字元
            public void write(char[] cbuf) 寫一個字元數組
            public void write(char[] cbuf, int off, int len) 寫一個字元數組的一部分
            public void write(String str) 寫一個字元串
            public void write(String str, int off, int len) 寫一個字元串的一部分
    (6)字元轉換流的2種讀資料的方式
        InputStreamReader類的成員方法:
            public int read() 一次讀取一個字元
                傳回值是下一個資料字元,如果已到檔案末尾,則傳回-1。
            public int read(char[] chs) 一次讀取一個字元數組
                傳回值是實際讀取的字元個數,如果已到檔案末尾,則傳回-1。
---------------------------------------
    (7)面試題:
        close()和flush()的差別?
            A:close()關閉流對象,但是先重新整理一次緩沖區。流對象關閉之後,流對象不可以再繼續使用了。
            B:flush()僅僅是重新整理緩沖區,重新整理之後,流對象還可以繼續使用。
    (8)字元轉換流(= 字元流 = 轉換流) ==> 字元轉換簡化流 ==> 字元流
        字元轉換流的簡化寫法
            FileWriter
            FileReader
        由于我們常見的操作都是使用本地預設編碼,是以,不用指定編碼。
        而字元轉換流的名稱有點長,是以,為了簡化我們的書寫,Java就提供了字元轉換流的子類供我們使用。
            OutputStreamWriter = FileOutputStream + 本地預設編碼
                ||
            FileWriter = FileOutputStream + 本地預設編碼
                
            InputStreamReader = FileInputStream + 本地預設編碼
                ||
            FileReader = FileInputStream + 本地預設編碼
    (9)字元緩沖區流
        字元流為了高效讀寫,也提供了對應的字元緩沖區流。
            BufferedWriter:字元緩沖區輸出流
            BufferedReader:字元緩沖區輸入流
        字元緩沖區流的特殊方法:
            BufferedWriter類的方法:
                public void newLine() 根據系統屬性來決定換行符
            BufferedReader類的方法:
                public String readLine() 一次讀取一行資料(字元串)
                    傳回值是:包含該行内容的字元串,不包含任何行終止符,如果已到達流末尾,則傳回 null。
      
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_05;
 2 
 3 import java.io.BufferedWriter;
 4 import java.io.FileWriter;
 5 import java.io.IOException;
 6 
 7 /*
 8  * 字元流為了高效讀寫,也提供了對應的字元緩沖區流。
 9  *         BufferedWriter:字元緩沖區輸出流
10  *         BufferedReader:字元緩沖區輸入流
11  * 
12  * BufferedWriter:字元緩沖區輸出流
13  *         将文本寫入字元輸出流,緩沖各個字元,進而提供單個字元、數組和字元串的高效寫入。 
14  *         可以指定緩沖區的大小,或者接受預設的大小。在大多數情況下,預設值就足夠大了。 
15  * 
16  * BufferedWriter類的構造方法
17  *         public BufferedWriter(Writer out)
18  */
19 public class BufferedWriterDemo {
20     public static void main(String[] args) throws IOException {
21         // 建立字元緩沖區輸出流對象
22         // public BufferedWriter(Writer out)
23         // BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("bw.txt")));
24         BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));
25 
26         bw.write("hello");
27         bw.write("world");
28         bw.write("java");
29         bw.flush();
30 
31         bw.close();
32     }
33 }      

BufferedWriterDemo.java

java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_05;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.FileReader;
 5 import java.io.IOException;
 6 
 7 /*
 8  * BufferedReader:字元緩沖區輸入流
 9  *         從字元輸入流中讀取文本,緩沖各個字元,進而實作字元、數組和行的高效讀取。 
10  *         可以指定緩沖區的大小,或者可使用預設的大小。大多數情況下,預設值就足夠大了。 
11  * 
12  * BufferedReader類的構造方法
13  *         public BufferedReader(Reader in)
14  */
15 public class BufferedReaderDemo {
16     public static void main(String[] args) throws IOException {
17         // 建立字元緩沖區輸入流對象
18         // public BufferedReader(Reader in)
19         // BufferedReader bw = new BufferedReader(new InputStreamReader(new FileInputStream("bw.txt")));
20         BufferedReader br = new BufferedReader(new FileReader("bw.txt"));
21 
22         // 方式1
23 //        int ch = 0;
24 //        while ((ch = br.read()) != -1) {
25 //            System.out.print((char) ch);
26 //        }
27 
28         // 方式2
29         char[] chs = new char[1024];
30         int len = 0;
31         while ((len = br.read(chs)) != -1) {
32             System.out.print(new String(chs, 0, len));
33         }
34 
35         // 釋放資源
36         br.close();
37     }
38 }      

BufferedReaderDemo.java

java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_05;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.BufferedWriter;
 5 import java.io.FileReader;
 6 import java.io.FileWriter;
 7 import java.io.IOException;
 8 
 9 /*
10  * 字元緩沖區流的特殊方法:
11  *         BufferedWriter類的方法:
12  *             public void newLine() 根據系統屬性來決定換行符
13  *         BufferedReader類的方法:
14  *             public String readLine() 一次讀取一行資料(字元串)
15  *                 傳回值是:包含該行内容的字元串,不包含任何行終止符,如果已到達流末尾,則傳回 null。
16  */
17 public class BufferedDemo {
18     public static void main(String[] args) throws IOException {
19         write();
20         read();
21     }
22 
23     private static void read() throws IOException {
24         // 建立字元緩沖輸入流對象(讀取資料)
25         BufferedReader br = new BufferedReader(new FileReader("bw2.txt"));
26 
27         // public String readLine() 一次讀取一行資料(字元串)
28         // String line = br.readLine(); 
29         // System.out.println(line); // hello1
30         // line = br.readLine();
31         // System.out.println(line); // hello2
32 
33         // 最終版代碼,循環改進
34         String line = null;
35         while ((line = br.readLine()) != null) {
36             System.out.println(line);
37         }
38         
39         //釋放資源
40         br.close();
41     }
42 
43     private static void write() throws IOException {
44         // 建立字元緩沖輸出流對象(寫資料)
45         BufferedWriter bw = new BufferedWriter(new FileWriter("bw2.txt"));
46         for (int x = 0; x < 100; x++) {
47             bw.write("hello" + x); // bw.write("\r\n"); // 在windows系統下的換行
48             bw.newLine(); // 根據系統屬性來決定換行符
49             bw.flush(); // 習慣性寫法
50         }
51         bw.close();
52     }
53 
54 }      

BufferedDemo.java

需求:把 目前項目目錄下的a.txt内容 複制到 目前項目目錄下的b.txt 中      
1 package cn.itcast_06;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.BufferedWriter;
 5 import java.io.FileReader;
 6 import java.io.FileWriter;
 7 import java.io.IOException;
 8 
 9 /*
10  * 需求:把 目前項目目錄下的a.txt内容 複制到 目前項目目錄下的b.txt 中
11  * 
12  * 資料源:                                                        字元轉換流的簡化寫法    字元緩沖區流(高效字元流)
13  *         a.txt --> 讀取資料 --> 字元轉換流 --> InputStreamReader --> FileReader --> BufferedReader
14  * 目的地:
15  *         b.txt --> 寫出資料 --> 字元轉換流 --> OutputStreamWriter --> FileWriter --> BufferedWriter
16  */
17 public class CopyFileDemo {
18     public static void main(String[] args) throws IOException {
19         // 封裝資料源
20         BufferedReader br = new BufferedReader(new FileReader("a.txt"));
21         // 封裝目的地
22         BufferedWriter bw = new BufferedWriter(new FileWriter("b.txt"));
23 
24         // 兩種方式其中的一種
25         // 一次讀寫一個字元數組
26         char[] chs = new char[1024];
27         int len = 0;
28         while ((len = br.read(chs)) != -1) {
29             bw.write(chs, 0, len);
30             bw.flush();
31         }
32 
33         // 釋放資源
34         bw.close();
35         br.close();
36     }
37 }      
需求:把 目前項目目錄下的a.txt内容 複制到 目前項目目錄下的b.txt 中
使用字元緩沖區流的特殊讀寫方法      
1 package cn.itcast_06;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.BufferedWriter;
 5 import java.io.FileReader;
 6 import java.io.FileWriter;
 7 import java.io.IOException;
 8 
 9 /*
10  * 需求:把 目前項目目錄下的a.txt内容 複制到 目前項目目錄下的b.txt 中
11  * 
12  * 使用字元緩沖區流的特殊讀寫方法
13  * 
14  * 資料源:
15  *         a.txt --> 讀取資料 --> 字元轉換流 --> InputStreamReader --> FileReader --> BufferedReader
16  * 目的地:
17  *         b.txt --> 寫出資料 --> 字元轉換流 --> OutputStreamWriter --> FileWriter --> BufferedWriter
18  */
19 public class CopyFileDemo2 {
20     public static void main(String[] args) throws IOException {
21         // 封裝資料源
22         BufferedReader br = new BufferedReader(new FileReader("a.txt"));
23         // 封裝目的地
24         BufferedWriter bw = new BufferedWriter(new FileWriter("b.txt"));
25 
26         // 讀寫資料,一次讀寫一行資料(字元串)(要與newLine()方法配合使用)
27         String line = null;
28         while ((line = br.readLine()) != null) {
29             bw.write(line); // 一次寫一行資料(字元串)(要與newLine()方法配合使用)
30             bw.newLine(); // 根據系統屬性來決定換行符
31             bw.flush();
32         }
33 
34         // 釋放資源
35         bw.close();
36         br.close();
37     }
38 }      
---------------------------------------
    (10)字元流
        Reader(抽象類)
            |--FilterReader(抽象類:字元過濾輸入流)
            |--InputStreamReader(字元轉換輸入流)
                |--FileReader(字元轉換輸入流的簡化寫法)
            |--BufferedReader(字元緩沖區輸入流)
        Writer(抽象類)
            |--FilterWriter(抽象類:字元過濾輸出流)
            |--OutputStreamWriter(字元轉換輸出流)
                |--FileWriter(字元轉換輸出流的簡化寫法)
            |--BufferedWriter(字元緩沖區輸出流)
-----------------------------------------------------------------------------
2:IO流小結(掌握)
    IO流
        |--位元組流
            |--位元組輸入流
                InputStream
                    int read() 一次讀取一個位元組
                    int read(byte[] bys) 一次讀取一個位元組數組
                
                    |--FileInputStream
                    |--BufferedInputStream
            |--位元組輸出流
                OutputStream
                    void write(int by) 一次寫一個位元組
                    void write(byte[] bys, int index, int len) 一次寫一個位元組數組的一部分
                    
                    |--FileOutputStream
                    |--BufferedOutputStream
                    
        |--字元流
            |--字元輸入流
                Reader
                    int read() 一次讀取一個字元
                    int read(char[] chs) 一次讀取一個字元數組
                    
                    |--InputStreamReader
                        |--FileReader
                    |--BufferedReader
                        String readLine() 一次讀取一行資料(字元串)
            |--字元輸出流
                Writer
                    void write(int ch) 一次寫一個字元
                    void write(char[] chs, int index, int len) 一次寫一個字元數組的一部分
                    
                    |--OutputStreamWriter
                        |--FileWriter
                    |--BufferedWriter
                        void newLine() 寫一個換行符
                        
                    void write(String line) 一次寫一行資料(字元串)(要與newLine()方法配合使用)
-----------------------------------------------------------------------------
3:案例(掌握)
    A:複制文本檔案(用字元流) 5種方式(掌握)
        基本字元流兩種
        高效字元緩沖區流兩種
        特殊字元緩沖區流一種
      複制文本檔案(用字元流和用位元組流) 9種方式
      
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_01;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.BufferedWriter;
  5 import java.io.File;
  6 import java.io.FileReader;
  7 import java.io.FileWriter;
  8 import java.io.IOException;
  9 
 10 /*
 11  * 複制文本檔案
 12  * 
 13  * 分析:
 14  *         複制資料,如果我們知道用windows自帶的記事本打開并能夠讀懂的檔案,就用字元流,否則用位元組流。
 15  *         通過該原理,我們知道我們應該采用字元流更友善一些。
 16  *         而字元流有5種方式,是以做這個題目我們有5種方式。推薦掌握第5種。
 17  * 資料源:
 18  *         c:\\a.txt --> FileReader --> BufferdReader
 19  * 目的地:
 20  *         d:\\b.txt --> FileWriter --> BufferedWriter
 21  */
 22 public class CopyFileDemo {
 23     public static void main(String[] args) throws IOException {
 24         // 使用字元串作為路徑(簡潔寫法)
 25         String srcString = "c:\\a.jpg";
 26         String destString = "d:\\b.jpg";
 27         
 28         // 使用File對象作為參數(裝逼/專業寫法)
 29         // File srcFile = new File("c:\\a.jpg");
 30         // File destFile = new File("d:\\b.jpg");
 31         // 是檔案和目錄(檔案夾)路徑名的抽象表示形式。僅僅是一個路徑的表示,不代表具體的事物一定是存在的。
 32         
 33         // method1(srcString, destString);
 34         // method2(srcString, destString);
 35         // method3(srcString, destString);
 36         // method4(srcString, destString);
 37         method5(srcString, destString);
 38     }
 39 
 40     // 字元緩沖區流:一次讀寫一行資料(字元串)
 41     private static void method5(String srcString, String destString) throws IOException {
 42         BufferedReader br = new BufferedReader(new FileReader(srcString));
 43         BufferedWriter bw = new BufferedWriter(new FileWriter(destString));
 44 
 45         String line = null;
 46         while ((line = br.readLine()) != null) {
 47             bw.write(line); // 一次寫一行資料(字元串)(要與newLine()方法配合使用)
 48             bw.newLine();
 49             bw.flush();
 50         }
 51 
 52         bw.close();
 53         br.close();
 54     }
 55 
 56     // 字元緩沖區流:一次讀寫一個字元數組
 57     private static void method4(String srcString, String destString) throws IOException {
 58         BufferedReader br = new BufferedReader(new FileReader(srcString));
 59         BufferedWriter bw = new BufferedWriter(new FileWriter(destString));
 60 
 61         char[] chs = new char[1024];
 62         int len = 0;
 63         while ((len = br.read(chs)) != -1) {
 64             bw.write(chs, 0, len);
 65         }
 66 
 67         bw.close();
 68         br.close();
 69     }
 70 
 71     // 字元緩沖區流:一次讀寫一個字元
 72     private static void method3(String srcString, String destString) throws IOException {
 73         BufferedReader br = new BufferedReader(new FileReader(srcString));
 74         BufferedWriter bw = new BufferedWriter(new FileWriter(destString));
 75 
 76         int ch = 0;
 77         while ((ch = br.read()) != -1) {
 78             bw.write(ch);
 79         }
 80 
 81         bw.close();
 82         br.close();
 83     }
 84 
 85     // 基本字元流:一次讀寫一個字元數組
 86     private static void method2(String srcString, String destString) throws IOException {
 87         FileReader fr = new FileReader(srcString);
 88         FileWriter fw = new FileWriter(destString);
 89 
 90         char[] chs = new char[1024];
 91         int len = 0;
 92         while ((len = fr.read(chs)) != -1) {
 93             fw.write(chs, 0, len);
 94         }
 95 
 96         fw.close();
 97         fr.close();
 98     }
 99 
100     // 基本字元流:一次讀寫一個字元
101     private static void method1(String srcString, String destString) throws IOException {
102         FileReader fr = new FileReader(srcString);
103         FileWriter fw = new FileWriter(destString);
104 
105         int ch = 0;
106         while ((ch = fr.read()) != -1) {
107             fw.write(ch);
108         }
109 
110         fw.close();
111         fr.close();
112     }
113 }      

複制文本檔案(用字元流) 5種方式

---------------------------------------        
    B:複制圖檔/視訊/音頻(用位元組流) 4種方式(掌握)
        基本位元組流兩種
        高效位元組緩沖區流兩種
      
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_01;
 2 
 3 import java.io.BufferedInputStream;
 4 import java.io.BufferedOutputStream;
 5 import java.io.File;
 6 import java.io.FileInputStream;
 7 import java.io.FileOutputStream;
 8 import java.io.IOException;
 9 
10 /*
11  * 複制圖檔
12  * 
13  * 分析:
14  *         複制資料,如果我們知道用記事本打開并能夠讀懂,就用字元流,否則用位元組流。
15  *         通過該原理,我們知道我們應該采用位元組流。
16  *         而位元組流有4種方式,是以做這個題目我們有4種方式。推薦掌握第4種。
17  * 
18  * 資料源:
19  *         c:\\a.jpg --> FileInputStream --> BufferedInputStream
20  * 目的地:
21  *         d:\\b.jpg --> FileOutputStream --> BufferedOutputStream
22  */
23 public class CopyImageDemo {
24     public static void main(String[] args) throws IOException {
25         // 使用字元串作為路徑(簡潔寫法)
26         // String srcString = "c:\\a.jpg";
27         // String destString = "d:\\b.jpg";
28         
29         // 使用File對象作為參數(裝逼/專業寫法)
30         File srcFile = new File("c:\\a.jpg");
31         File destFile = new File("d:\\b.jpg");
32         // 是檔案和目錄(檔案夾)路徑名的抽象表示形式。僅僅是一個路徑的表示,不代表具體的事物一定是存在的。
33         
34         // method1(srcFile, destFile);
35         // method2(srcFile, destFile);
36         // method3(srcFile, destFile);
37         method4(srcFile, destFile);
38     }
39 
40     // 位元組緩沖區流:一次讀寫一個位元組數組
41     private static void method4(File srcFile, File destFile) throws IOException {
42         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
43         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
44 
45         byte[] bys = new byte[1024];
46         int len = 0;
47         while ((len = bis.read(bys)) != -1) {
48             bos.write(bys, 0, len);
49         }
50 
51         bos.close();
52         bis.close();
53     }
54 
55     // 位元組緩沖強區流:一次讀寫一個位元組
56     private static void method3(File srcFile, File destFile) throws IOException {
57         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
58         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
59 
60         int by = 0;
61         while ((by = bis.read()) != -1) {
62             bos.write(by);
63         }
64 
65         bos.close();
66         bis.close();
67     }
68 
69     // 基本位元組流:一次讀寫一個位元組數組
70     private static void method2(File srcFile, File destFile) throws IOException {
71         FileInputStream fis = new FileInputStream(srcFile);
72         FileOutputStream fos = new FileOutputStream(destFile);
73 
74         byte[] bys = new byte[1024];
75         int len = 0;
76         while ((len = fis.read(bys)) != -1) {
77             fos.write(bys, 0, len);
78         }
79 
80         fos.close();
81         fis.close();
82     }
83 
84     // 基本位元組流:一次讀寫一個位元組
85     private static void method1(File srcFile, File destFile) throws IOException {
86         FileInputStream fis = new FileInputStream(srcFile);
87         FileOutputStream fos = new FileOutputStream(destFile);
88 
89         int by = 0;
90         while ((by = fis.read()) != -1) {
91             fos.write(by);
92         }
93 
94         fos.close();
95         fis.close();
96     }
97 }      

複制圖檔/視訊/音頻(用位元組流) 4種方式

---------------------------------------        
    C:把ArrayList集合中的資料存儲到文本檔案
        隻有寫出資料,沒有讀取資料。
      
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_02;
 2 
 3 import java.io.BufferedWriter;
 4 import java.io.FileWriter;
 5 import java.io.IOException;
 6 import java.util.ArrayList;
 7 
 8 /*
 9  * 需求:把ArrayList集合中的字元串資料存儲到文本檔案
10  * 
11  * 分析:
12  *         通過題目的意思我們可以知道如下的一些内容:
13  *             
14  *             隻有寫出資料,沒有讀取資料。
15  * 
16  *             ArrayList集合裡存儲的是字元串。
17  *             周遊ArrayList集合,把資料擷取到。
18  *             然後存儲到文本檔案中。
19  * 
20  *             文本檔案說明使用字元流。
21  * 
22  * 資料源:
23  *         ArrayList<String> --> 周遊得到每一個字元串資料
24  * 目的地:
25  *         a.txt --> FileWriter --> BufferedWriter
26  */
27 public class ArrayListToFileDemo {
28     public static void main(String[] args) throws IOException {
29         // 封裝資料源(建立集合對象)
30         ArrayList<String> array = new ArrayList<String>();
31         array.add("hello");
32         array.add("world");
33         array.add("java");
34 
35         // 封裝目的地
36         BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));
37 
38         // 周遊集合(增強for)
39         for (String s : array) {
40             // 寫資料
41             bw.write(s);
42             bw.newLine();
43             bw.flush();
44         }
45 
46         // 釋放資源
47         bw.close();
48     }
49 }      

把ArrayList集合中的資料存儲到文本檔案

---------------------------------------        
    D:從文本檔案中讀取資料(每一行為一個字元串資料)到ArrayList集合中,并周遊集合
        隻有讀取資料,沒有寫出資料。
      
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_02;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.FileReader;
 5 import java.io.IOException;
 6 import java.util.ArrayList;
 7 
 8 /*
 9  * 需求:從文本檔案中讀取資料(每一行為一個字元串資料)到集合中,并周遊集合
10  * 
11  * 分析:
12  *         通過題目的意思我們可以知道如下的一些内容:
13  * 
14  *             隻有讀取資料,沒有寫出資料。
15  * 
16  *             資料源是一個文本檔案。
17  *             目的地是一個集合。
18  *             而且元素是字元串。
19  * 
20  * 資料源:
21  *         b.txt --> FileReader --> BufferedReader
22  * 目的地:
23  *         ArrayList<String>
24  */
25 public class FileToArrayListDemo {
26     public static void main(String[] args) throws IOException {
27         // 封裝資料源
28         BufferedReader br = new BufferedReader(new FileReader("b.txt"));
29         // 封裝目的地(建立集合對象)
30         ArrayList<String> array = new ArrayList<String>();
31 
32         // 讀取資料存儲到集合中
33         String line = null;
34         while ((line = br.readLine()) != null) {
35             array.add(line);
36         }
37 
38         // 釋放資源
39         br.close();
40 
41         // 周遊集合(增強for)
42         for (String s : array) {
43             System.out.println(s);
44         }
45         
46     }
47 }      

從文本檔案中讀取資料(每一行為一個字元串資料)到ArrayList集合中,并周遊集合

---------------------------------------        
    E:我有一個文本檔案中存儲了幾個名字,請大家寫一個程式實作随機擷取一個人的名字。
        1:把文本檔案中的資料存儲到集合中
        2:随機産生一個索引,并設定索引的範圍
        3:根據該索引擷取一個值
      
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_02;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.FileReader;
 5 import java.io.IOException;
 6 import java.util.ArrayList;
 7 import java.util.Random;
 8 
 9 /*
10  * 需求:我有一個文本檔案中存儲了幾個名字,請大家寫一個程式實作随機擷取一個人的名字。
11  * 
12  * 分析:
13  *         A:把文本檔案中的資料存儲到集合中
14  *         B:随機産生一個索引,并設定索引的範圍
15  *         C:根據該索引擷取一個值
16  */
17 public class GetName {
18     public static void main(String[] args) throws IOException {
19         // 把文本檔案中的資料存儲到集合中
20         BufferedReader br = new BufferedReader(new FileReader("name.txt"));
21         ArrayList<String> array = new ArrayList<String>();
22         
23         String line = null;
24         while ((line = br.readLine()) != null) {
25             array.add(line);
26         }
27         br.close();
28 
29         // 随機産生一個索引,并設定索引的範圍
30         Random r = new Random();
31         int index = r.nextInt(array.size()); // [0, array.size())
32 
33         // 根據該索引擷取一個值
34         String name = array.get(index);
35         System.out.println("該幸運者是:" + name);
36     }
37 }      

我有一個文本檔案中存儲了幾個名字,請大家寫一個程式實作随機擷取一個人的名字

---------------------------------------        
    F:複制指定單級檔案夾中的所有檔案(裡面隻有檔案,且檔案各種各樣)
        1:封裝資料源File對象+封裝目的地File對象
        2:擷取資料源目錄下的所有檔案的File數組
        3:周遊該File數組,得到每一個File對象,通過該對象得到一個新的檔案路徑名的抽象表示
        4:把該File進行複制
      
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_03;
 2 
 3 import java.io.BufferedInputStream;
 4 import java.io.BufferedOutputStream;
 5 import java.io.File;
 6 import java.io.FileInputStream;
 7 import java.io.FileOutputStream;
 8 import java.io.IOException;
 9 
10 /*
11  * 需求:複制指定單極檔案夾中的所有檔案(裡面隻有檔案,且檔案各種各樣)
12  * 
13  *         用位元組流
14  * 
15  * 資料源:e:\\demo
16  * 目的地:e:\\test
17  * 
18  * 分析:
19  *         A:封裝資料源File對象+封裝目的地File對象
20  *         B:擷取資料源目錄下的所有檔案的File數組
21  *         C:周遊該File數組,得到每一個File對象,通過該對象得到一個新的檔案路徑名的抽象表示
22  *         D:把該File進行複制
23  */
24 public class CopyFolderDemo {
25     public static void main(String[] args) throws IOException {
26         // 封裝資料源File對象
27         File srcFolder = new File("e:\\demo");
28         // 封裝目的地File對象
29         File destFolder = new File("e:\\test");
30         // 如果目的地檔案夾不存在,就建立
31         if (!destFolder.exists()) {
32             destFolder.mkdir();
33         }
34 
35         // 擷取資料源目錄下的所有檔案的File數組
36         // 周遊該File數組,得到每一個File對象,通過該對象得到一個新的檔案路徑名的抽象表示
37         // 把該File進行複制
38         File[] fileArray = srcFolder.listFiles();
39         for (File srcFile : fileArray) {
40             // System.out.println(file); // e:\demo\e.mp3
41             // 資料源:e:\\demo\\e.mp3    注意:資料源是變化的
42             // 目的地:e:\\test\\e.mp3    注意:目的地也是變化的(使用拼接)
43             String name = srcFile.getName(); // e.mp3
44             File destFile = new File(destFolder, name); // e:\\test\\e.mp3
45 
46             copyFile(srcFile, destFile);
47         }
48     }
49 
50     private static void copyFile(File srcFile, File destFile) throws IOException {
51         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
52         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
53 
54         byte[] bys = new byte[1024];
55         int len = 0;
56         while ((len = bis.read(bys)) != -1) {
57             bos.write(bys, 0, len);
58         }
59 
60         bos.close();
61         bis.close();
62     }
63 }      

複制指定單級檔案夾中的所有檔案(裡面隻有檔案,且檔案各種各樣)

---------------------------------------        
    G:複制指定單級檔案夾中的指定的檔案,并修改檔案字尾名(裡面隻有檔案,且檔案各種各樣,但是本例題為了增加一點難度,使該單級檔案夾中增加一個檔案夾名為hello.java的檔案夾)
        1:封裝資料源File對象+封裝目的地File對象
        2:擷取資料源目錄下的所有.java檔案的File數組(加入了判斷條件)
        3:周遊該File數組,得到每一個File對象,通過該對象得到一個新的檔案路徑名的抽象表示
        4:把符合條件的File進行複制
        5:擷取目的地目錄下的所有檔案的File數組
        6:周遊該File數組,得到每一個File對象,通過該對象得到一個新的檔案路徑名的抽象表示
        7:把該File重命名為新名字      
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_04;
 2 
 3 import java.io.BufferedInputStream;
 4 import java.io.BufferedOutputStream;
 5 import java.io.File;
 6 import java.io.FileInputStream;
 7 import java.io.FileOutputStream;
 8 import java.io.FilenameFilter;
 9 import java.io.IOException;
10 
11 /*
12  * 需求:複制指定單級檔案夾中的指定檔案,并修改檔案字尾名(裡面隻有檔案,且檔案各種各樣,但是本例題為了增加一點難度,使該單級檔案夾中增加一個檔案夾名為hello.java的檔案夾)
13  *         
14  *         指定的檔案是:.java檔案
15  *         指定的字尾名是:.jad
16  *         指定的目錄是:jad
17  * 
18  * 資料源:e:\\java\\A.java
19  * 目的地:e:\\jad\\A.jad
20  * 
21  * 分析:
22  *         A:封裝資料源File對象+封裝目的地File對象
23  *         B:擷取資料源目錄下的所有.java檔案的File數組(加入了判斷條件)
24  *         C:周遊該File數組,得到每一個File對象,通過該對象得到一個新的檔案路徑名的抽象表示
25  *         D:把符合條件的File進行複制
26  *         E:擷取目的地目錄下的所有檔案的File數組
27  *         F:周遊該File數組,得到每一個File對象,通過該對象得到一個新的檔案路徑名的抽象表示
28  *         E:把該File重命名為新名字
29  */
30 public class CopyFolderDemo {
31     public static void main(String[] args) throws IOException {
32         // 封裝資料源File對象
33         File srcFolder = new File("e:\\java");
34         // 封裝目的地File對象
35         File destFolder = new File("e:\\jad");
36         // 如果目的地目錄不存在,就建立
37         if (!destFolder.exists()) {
38             destFolder.mkdir();
39         }
40 
41         // 擷取資料源目錄下的所有.java檔案的File數組(加入了判斷條件)
42         File[] fileArray = srcFolder.listFiles(new FilenameFilter() {
43             @Override
44             public boolean accept(File dir, String name) {
45                 return new File(dir, name).isFile() && name.endsWith(".java");
46             }
47         });
48 
49         // 周遊該File數組,得到每一個File對象,通過該對象得到一個新的檔案路徑名的抽象表示
50         // 把符合條件的File進行複制
51         for (File srcFile : fileArray) {
52             // System.out.println(file); // e:\java\DataTypeDemo.java
53             // 資料源:e:\\java\\DataTypeDemo.java     注意:資料源是變化的
54             // 目的地:e:\\jad\\DataTypeDemo.java     注意:目的地也是變化的(使用拼接)
55             String name = srcFile.getName(); // DataTypeDemo.java
56             File destFile = new File(destFolder, name); // e:\\jad\\DataTypeDemo.java
57 
58             copyFile(srcFile, destFile);
59         }
60 
61         // 擷取目的地目錄下的所有檔案的File數組
62         // 周遊該File數組,得到每一個File對象,通過該對象得到一個新的檔案路徑名的抽象表示
63         // 把該File重命名為新名字
64         File[] destFileArray = destFolder.listFiles();
65         for (File destFile : destFileArray) {
66             // System.out.println(destFile); // e:\jad\DataTypeDemo.java
67             // 資料源:e:\\jad\\DataTypeDemo.java
68             // 目的地:e:\\jad\\DataTypeDemo.jad
69             String oldName = destFile.getName(); // DataTypeDemo.java
70             String newName = oldName.replace(".java", ".jad"); // DataTypeDemo.jad
71             File newFile = new File(destFolder, newName); // e:\\jad\\DataTypeDemo.jad
72             
73             destFile.renameTo(newFile);
74         }
75     }
76 
77     private static void copyFile(File srcFile, File destFile) throws IOException {
78         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
79         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
80 
81         byte[] bys = new byte[1024];
82         int len = 0;
83         while ((len = bis.read(bys)) != -1) {
84             bos.write(bys, 0, len);
85         }
86 
87         bos.close();
88         bis.close();
89     }
90 }      

複制指定單級檔案夾中的指定的檔案,并修改檔案字尾名

回顧:批量修改檔案名稱代碼和視訊(day19)
      
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_09;
 2 
 3 import java.io.File;
 4 
 5 /*
 6  * 需求:把E:\評書\三國演義下面的視訊名稱修改為
 7  *         00?_介紹.avi
 8  * 
 9  * 思路:
10  *         A:把 E:\\評書\\三國演義 封裝成一個File對象
11  *         B:擷取該目錄下所有的檔案的File數組
12  *         C:周遊該File數組,得到每一個File對象,該對象名列印輸出為:E:\\評書\\三國演義\\三國演義_001_[評書網-今天很高興,明天就IO了]_桃園三結義.avi
13  *         D:擷取符合要求的各個名稱
14  *         E:拼接一個新的名稱,再new一個新對象,新對象名列印輸出為: E:\\評書\\三國演義\\001_桃園三結義.avi
15  *         F:然後重命名即可。
16  */
17 public class FileDemo {
18     public static void main(String[] args) {
19         // 把 E:\\評書\\三國演義 封裝成一個File對象
20         File srcFolder = new File("E:\\評書\\三國演義");
21 
22         // 擷取該目錄下所有的檔案的File數組
23         File[] fileArray = srcFolder.listFiles();
24 
25         // 周遊該File數組,得到每一個File對象
26         for (File file : fileArray) {
27             // System.out.println(file); 
28             
29             // 改前:E:\評書\三國演義\三國演義_001_[評書網-今天很高興,明天就IO了]_桃園三結義.avi
30             // 改後:E:\評書\三國演義\001_桃園三結義.avi
31             
32             String name = file.getName(); // 三國演義_001_[評書網-今天很高興,明天就IO了]_桃園三結義.avi
33 
34             int index = name.indexOf("_"); // 找到第一個_
35             String numberString = name.substring(index + 1, index + 4); // 001    包左不包右 
36             // System.out.println(numberString); // 001
37             
38             int endIndex = name.lastIndexOf('_'); // 找到最後一個_
39             String nameString = name.substring(endIndex); // 桃園三結義.avi
40             // System.out.println(nameString); // 桃園三結義.avi
41             
42             // 拼接一個新的名稱
43             String newName = numberString.concat(nameString); // 001_桃園三結義.avi
44             // System.out.println(newName); // 001_桃園三結義.avi
45 
46             // 把 E:\\評書\\三國演義\\001_桃園三結義.avi 封裝成一個File對象
47             File newFile = new File(srcFolder, newName); // E:\\評書\\三國演義\\001_桃園三結義.avi
48             // System.out.println(newFile);
49             
50             // 重命名即可
51             file.renameTo(newFile);
52         }
53     }
54 }      

批量修改檔案名稱代碼

---------------------------------------        
    H:複制多級檔案夾
        1:封裝資料源File對象+封裝目的地File對象
        2:判斷該資料源File對象是檔案夾還是檔案
            a:是檔案夾
                就在目的地目錄下建立該檔案夾(建立前先拼接一個新的檔案夾路徑名的抽象表示)
                擷取該資料源File對象下的所有檔案或者檔案夾的File數組
                周遊該File數組,得到每一個File對象
                回到B(遞歸)
            b:是檔案(檔案各種各樣,用位元組流複制)
                就在目的地目錄下複制該檔案(複制前先拼接一個新的檔案路徑名的抽象表示)
      
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_05;
 2 
 3 import java.io.BufferedInputStream;
 4 import java.io.BufferedOutputStream;
 5 import java.io.File;
 6 import java.io.FileInputStream;
 7 import java.io.FileOutputStream;
 8 import java.io.IOException;
 9 
10 /*
11  * 需求:複制多級檔案夾
12  * 
13  * 資料源:E:\JavaSE\day21\code\demos
14  * 目的地:E:\\
15  * 
16  * 分析:
17  *         A:封裝資料源File對象+封裝目的地File對象
18  *         B:判斷該資料源File對象是檔案夾還是檔案
19  *             a:是檔案夾
20  *                 就在目的地目錄下建立該檔案夾(建立前先拼接一個新的檔案夾路徑名的抽象表示)
21  *                 擷取該資料源File對象下的所有檔案或者檔案夾的File數組
22  *                 周遊該File數組,得到每一個File對象
23  *                 回到B(遞歸)
24  *             b:是檔案(檔案各種各樣,用位元組流複制)
25  *                 就在目的地目錄下複制該檔案(複制前先拼接一個新的檔案路徑名的抽象表示)
26  */
27 public class CopyFoldersDemo {
28     public static void main(String[] args) throws IOException {
29         // 封裝資料源File對象
30         File srcFile = new File("E:\\JavaSE\\day21\\code\\demos");
31         // 封裝目的地File對象
32         File destFile = new File("E:\\");
33 
34         // 複制檔案夾的功能
35         copyFolder(srcFile, destFile);
36     }
37 
38     private static void copyFolder(File srcFile, File destFile) throws IOException {
39         // 判斷該資料源File對象是檔案夾還是檔案
40         if (srcFile.isDirectory()) {
41             // 是檔案夾
42             // 就在目的地目錄下建立該檔案夾(建立前先拼接一個新的檔案夾路徑名的抽象表示)
43             File newFolder = new File(destFile, srcFile.getName());
44             newFolder.mkdir(); // 因為檔案夾不會幫你自動建立,需要你手動建立
45 
46             // 擷取該資料源File對象下的所有檔案或者檔案夾的File數組
47             // 周遊該File數組,得到每一個File對象
48             File[] fileArray = srcFile.listFiles();
49             for (File file : fileArray) {
50                 copyFolder(file, newFolder);
51             }
52         } else {
53             // 是檔案(檔案各種各樣,用位元組流複制)
54             // 就在目的地目錄下複制該檔案(複制前先拼接一個新的檔案路徑名的抽象表示)
55             File newFile = new File(destFile, srcFile.getName());
56             copyFile(srcFile, newFile);
57         }
58     }
59 
60     // 複制檔案的功能
61     private static void copyFile(File srcFile, File newFile) throws IOException {
62         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
63         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));
64 
65         byte[] bys = new byte[1024];
66         int len = 0;
67         while ((len = bis.read(bys)) != -1) {
68             bos.write(bys, 0, len);
69         }
70 
71         bos.close();
72         bis.close();
73     }
74 }      

複制多級檔案夾

---------------------------------------    
    I:鍵盤錄入5個學生資訊(姓名,國文成績,數學成績,英語成績),按照總分從高到低存入文本檔案。
        1:建立學生類
        2:建立集合對象(比較器排序:匿名内部類實作)
            TreeSet<Student>
        3:鍵盤錄入學生資訊并存儲到集合
        4:周遊集合,把資料寫到文本檔案      
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_06;
 2 
 3 public class Student {
 4     // 姓名
 5     private String name;
 6     // 國文成績
 7     private int chinese;
 8     // 數學成績
 9     private int math;
10     // 英語成績
11     private int english;
12 
13     public Student() {
14         super();
15     }
16 
17     public Student(String name, int chinese, int math, int english) {
18         super();
19         this.name = name;
20         this.chinese = chinese;
21         this.math = math;
22         this.english = english;
23     }
24 
25     public String getName() {
26         return name;
27     }
28 
29     public void setName(String name) {
30         this.name = name;
31     }
32 
33     public int getChinese() {
34         return chinese;
35     }
36 
37     public void setChinese(int chinese) {
38         this.chinese = chinese;
39     }
40 
41     public int getMath() {
42         return math;
43     }
44 
45     public void setMath(int math) {
46         this.math = math;
47     }
48 
49     public int getEnglish() {
50         return english;
51     }
52 
53     public void setEnglish(int english) {
54         this.english = english;
55     }
56 
57     public int getSum() {
58         return this.chinese + this.math + this.english;
59     }
60 }      

Student.java

java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_06;
 2 
 3 import java.io.BufferedWriter;
 4 import java.io.FileWriter;
 5 import java.io.IOException;
 6 import java.util.Comparator;
 7 import java.util.Scanner;
 8 import java.util.TreeSet;
 9 
10 /*
11  * 鍵盤錄入5個學生資訊(姓名,國文成績,數學成績,英語成績),按照總分從高到低存入文本檔案。
12  * 
13  * 分析:
14  *         A:建立學生類
15  *         B:建立集合對象(比較器排序:匿名内部類實作)
16  *             TreeSet<Student>
17  *         C:鍵盤錄入學生資訊并存儲到集合
18  *         D:周遊集合,把資料寫到文本檔案
19  */
20 public class StudentDemo {
21     public static void main(String[] args) throws IOException {
22         // 建立集合對象(比較器排序:匿名内部類實作)
23         TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
24             @Override
25             public int compare(Student s1, Student s2) {
26                 int num = s2.getSum() - s1.getSum(); // 主要條件
27                 int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num; // 次要條件
28                 int num3 = num2 == 0 ? s1.getMath() - s2.getMath() : num2; // 次要條件
29                 int num4 = num3 == 0 ? s1.getEnglish() - s2.getEnglish() : num3; // 次要條件
30                 int num5 = num4 == 0 ? s1.getName().compareTo(s2.getName()) : num4; // 次要條件
31                 return num5; 
32             }
33         });
34 
35         // 鍵盤錄入學生資訊并存儲到集合
36         Scanner sc = null;
37         for (int x = 1; x <= 5; x++) {
38             sc = new Scanner(System.in);
39             System.out.println("請錄入第" + x + "個的學習資訊");
40             System.out.println("姓名:");
41             String name = sc.nextLine();
42             System.out.println("國文成績:");
43             int chinese = sc.nextInt();
44             System.out.println("數學成績:");
45             int math = sc.nextInt();
46             System.out.println("英語成績:");
47             int english = sc.nextInt();
48 
49             // 建立學生對象
50             Student s = new Student();
51             s.setName(name);
52             s.setChinese(chinese);
53             s.setMath(math);
54             s.setEnglish(english);
55 
56             // 把學生對象添加到集合
57             ts.add(s);
58         }
59         sc.close();
60 
61         // 周遊集合,把資料寫到文本檔案
62         BufferedWriter bw = new BufferedWriter(new FileWriter("students.txt"));
63         bw.write("學生資訊如下:");
64         bw.newLine();
65         bw.flush();
66         bw.write("姓名,國文成績,數學成績,英語成績");
67         bw.newLine();
68         bw.flush();
69         for (Student s : ts) {
70             StringBuilder sb = new StringBuilder();
71             sb.append(s.getName()).append(",").append(s.getChinese()).append(",").append(s.getMath()).append(",").append(s.getEnglish());
72             bw.write(sb.toString());
73             bw.newLine();
74             bw.flush();
75         }
76         // 釋放資源
77         bw.close();
78         System.out.println("學習資訊存儲完畢");
79     }
80 }      

鍵盤錄入5個學生資訊(姓名,國文成績,數學成績,英語成績),按照總分從高到低存入文本檔案

回顧:鍵盤錄入5個學生資訊(姓名,國文成績,數學成績,英語成績),按照總分從高到低輸出到控制台。(day17)
      
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_09;
 2 
 3 public class Student {
 4     // 姓名
 5     private String name;
 6     // 國文成績
 7     private int chinese;
 8     // 數學成績
 9     private int math;
10     // 英語成績
11     private int english;
12     
13     public Student() {
14         super();
15     }
16 
17     public Student(String name, int chinese, int math, int english) {
18         super();
19         this.name = name;
20         this.chinese = chinese;
21         this.math = math;
22         this.english = english;
23     }
24 
25     public String getName() {
26         return name;
27     }
28 
29     public void setName(String name) {
30         this.name = name;
31     }
32 
33     public int getChinese() {
34         return chinese;
35     }
36 
37     public void setChinese(int chinese) {
38         this.chinese = chinese;
39     }
40 
41     public int getMath() {
42         return math;
43     }
44 
45     public void setMath(int math) {
46         this.math = math;
47     }
48 
49     public int getEnglish() {
50         return english;
51     }
52 
53     public void setEnglish(int english) {
54         this.english = english;
55     }
56 
57     public int getSum() {
58         return this.chinese + this.math + this.english;
59     }
60 }      
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_09;
 2 
 3 import java.util.Comparator;
 4 import java.util.Scanner;
 5 import java.util.TreeSet;
 6 
 7 /*
 8  * 鍵盤錄入5個學生資訊(姓名,國文成績,數學成績,英語成績),按照總分從高到低輸出到控制台。
 9  * 
10  * 分析:
11  *         A:定義學生類
12  *         B:建立一個TreeSet集合(比較器排序:匿名内部類實作)
13  *             TreeSet<Student>
14  *         C:總分從高到底如何實作呢?        
15  *         D:鍵盤錄入5個學生資訊
16  *         E:周遊TreeSet集合
17  */
18 public class TreeSetDemo {
19     public static void main(String[] args) {
20         // 建立一個TreeSet集合(比較器排序:匿名内部類實作)
21         TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
22             @Override
23             public int compare(Student s1, Student s2) {
24                 // 總分從高到低
25                 int num = s2.getSum() - s1.getSum();
26                 // 總分相同的不一定國文相同
27                 int num2 = (num == 0 ? s1.getChinese() - s2.getChinese() : num);
28                 // 總分和國文相同的不一定數序相同
29                 int num3 = (num2 == 0 ? s1.getMath() - s2.getMath() : num2);
30                 // 總分、國文和數學相同的不一定英語相同
31                 int num4 = (num3 == 0 ? s1.getEnglish() - s2.getEnglish() : num3);
32                 // 總分、國文、數學和英語相同的姓名還不一定相同
33                 int num5 = (num4 == 0 ? s1.getName().compareTo(s2.getName()) : num4);
34                 return num5;
35             }
36         });
37 
38         System.out.println("學生資訊錄入開始");
39         // 鍵盤錄入5個學生資訊
40         Scanner sc = null;
41         for (int x = 1; x <= 5; x++) {
42             sc = new Scanner(System.in);
43             
44             System.out.println("請輸入第" + x + "個學生的姓名:");
45             String name = sc.nextLine();
46             
47             System.out.println("請輸入第" + x + "個學生的國文成績:");
48             String chineseString = sc.nextLine();
49             
50             System.out.println("請輸入第" + x + "個學生的數學成績:");
51             String mathString = sc.nextLine();
52             
53             System.out.println("請輸入第" + x + "個學生的英語成績:");
54             String englishString = sc.nextLine();
55 
56             // 把錄入的資料封裝到學生對象中
57             Student s = new Student();
58             s.setName(name);
59             s.setChinese(Integer.parseInt(chineseString)); // 把字元串類型轉換為int類型
60             s.setMath(Integer.parseInt(mathString));        // 把字元串類型轉換為int類型
61             s.setEnglish(Integer.parseInt(englishString)); // 把字元串類型轉換為int類型
62 
63             // 把學生對象添加到集合
64             ts.add(s);
65         }
66         sc.close();
67         
68         System.out.println("學生資訊錄入完畢");
69 
70         System.out.println("學習資訊從高到低排序如下:");
71         System.out.println("姓名\t國文成績\t數學成績\t英語成績");
72         // 周遊TreeSet集合
73         for (Student s : ts) {
74             System.out.println(s.getName() + "\t" + s.getChinese() + "\t" + s.getMath() + "\t" + s.getEnglish());
75         }
76     }
77 }      

鍵盤錄入5個學生資訊(姓名,國文成績,數學成績,英語成績),按照總分從高到低輸出到控制台

---------------------------------------    
    J:已知在s.txt檔案中有這樣的一個字元串:“hcexfgijkamdnoqrzstuvwybpl”,請編寫程式讀取s.txt檔案的資料内容,把讀取到的資料排序後寫入到ss.txt中。
        1:封裝資料源File對象
        2:讀取該File對象的内容,存儲到一個字元串中
        3:把字元串轉換為字元數組
        4:對字元數組進行排序(使用數組工具類的排序方法)
        5:把排序後的字元數組轉換為字元串(通過字元串的構造方法實作)
        6:封裝目的地File對象
        7:通過該File對象把字元串寫入到ss.txt中
      
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_07;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.BufferedWriter;
 5 import java.io.FileReader;
 6 import java.io.FileWriter;
 7 import java.io.IOException;
 8 import java.util.Arrays;
 9 
10 /*
11  * 已知在s.txt檔案中有這樣的一個字元串:“hcexfgijkamdnoqrzstuvwybpl”
12  * 請編寫程式讀取s.txt檔案的資料内容,把讀取到的資料排序後寫入到ss.txt中。
13  * 
14  * 分析:
15  *         A:封裝資料源File對象
16  *         B:讀取該File對象的内容,存儲到一個字元串中
17  *         C:把字元串轉換為字元數組
18  *         D:對字元數組進行排序(使用數組工具類的排序方法)
19  *         E:把排序後的字元數組轉換為字元串(通過字元串的構造方法實作)
20  *         F:封裝目的地File對象
21  *         G:通過該File對象把字元串寫入到ss.txt中
22  */
23 public class StringDemo {
24     public static void main(String[] args) throws IOException {
25         // 封裝資料源File對象
26         // 讀取該File對象的内容,存儲到一個字元串中
27         BufferedReader br = new BufferedReader(new FileReader("s.txt"));
28         String line = br.readLine();
29         br.close();
30 
31         // 把字元串轉換為字元數組
32         char[] chs = line.toCharArray();
33 
34         // 對字元數組進行排序(使用數組工具類的排序方法實作)
35         Arrays.sort(chs);
36 
37         // 把排序後的字元數組轉換為字元串(通過字元串的構造方法實作)
38         String s = new String(chs);
39 
40         // 封裝目的地File對象
41         // 通過該File對象把字元串寫入到ss.txt中
42         BufferedWriter bw = new BufferedWriter(new FileWriter("ss.txt"));
43         bw.write(s);
44         bw.newLine();
45         bw.flush();
46 
47         bw.close();
48     }
49 }      

已知在s.txt檔案中有這樣的一個字元串:“hcexfgijkamdnoqrzstuvwybpl”,請編寫程式讀取s.txt檔案的資料内容,把讀取到的資料排序後寫入到ss.txt中

---------------------------------------    
    K:用Reader來模拟BufferedReader的特有功能readLine()
        注意:測試MyBufferedReader的時候,你就把它當作BufferedReader一樣來使用就好。
      
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_08;
 2 
 3 import java.io.IOException;
 4 import java.io.Reader;
 5 
 6 /*
 7  * 用Reader來模拟BufferedReader的readLine()功能
 8  * 
 9  * readLine() 一次讀取一行,根據換行符判斷是否結束,隻傳回内容,不傳回換行符。
10  * 
11  *
12  * 思考:寫一個方法,傳回值是一個字元串。
13  * 
14  * 我要傳回一個字元串,我該怎麼辦呢? 
15  * 因為我們現在有一個Reader對象,是以我們必須去看看r對象能夠讀取什麼東西呢? 
16  * r對象有兩個讀取方法:一次讀取一個字元或者一次讀取一個字元數組。
17  * 
18  * 那麼,我們要傳回一個字元串,用哪個方法比較好呢? 
19  * 我們很容易想到用字元數組比較好,但是問題來了,就是這個字元數組的長度是多長呢?
20  * 根本就沒有辦法定義數組的長度,你定義多長都不合适。 是以,隻能選擇一次讀取一個字元。
21  * 
22  * 但是呢,用這種方式的時候,我們在讀取下一個字元的時候,上一個字元就丢失了。
23  * 是以,我們又應該定義一個臨時存儲空間把讀取過的字元給存儲起來。
24  * 
25  * 這個用誰比較合适呢?
26  * 數組、集合、字元串緩沖區三個可供選擇。
27  * 經過簡單的分析,最終選擇使用字元串緩沖區對象。并且使用的是StringBuilder。
28  * 
29  */
30 public class MyBufferedReader {
31     private Reader r;
32 
33     public MyBufferedReader(Reader r) {
34         this.r = r;
35     }
36     
37     public String readLine() throws IOException {
38         StringBuilder sb = new StringBuilder();
39         
40         // 做這個讀取最麻煩的是判斷結束,但是在結束之前應該是一直讀取,直到-1。
41         int ch = 0;
42         while ((ch = r.read()) != -1) { 
43             if (ch == '\r') {
44                 continue;
45             }
46 
47             if (ch == '\n') {
48                 return sb.toString(); 
49             } else {
50                 sb.append((char)ch); 
51             }
52         }
53 
54         // 如果原始資料最後一行沒有回車換行符(\r\n),讀取到的最好一行資料會丢失,是以判斷讀取到的最後一行的sb的長度,長度大于0說明有資料。
55         if (sb.length() > 0) {
56             return sb.toString();
57         }
58 
59         return null;
60     }
61 
62     /*
63      * 先寫一個關閉流的方法
64      */
65     public void close() throws IOException {
66         this.r.close();
67     }
68 }      

MyBufferedReader.java

java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_08;
 2 
 3 import java.io.FileReader;
 4 import java.io.IOException;
 5 
 6 /*
 7  * 注意:測試MyBufferedReader的時候,你就把它當作BufferedReader一樣來使用就好。
 8  */
 9 public class MyBufferedReaderDemo {
10     public static void main(String[] args) throws IOException {
11         MyBufferedReader mbr = new MyBufferedReader(new FileReader("my.txt"));
12 
13         String line = null;
14         while ((line = mbr.readLine()) != null) {
15             System.out.println(line);
16         }
17 
18         mbr.close();
19     }
20 }      

MyBufferedReaderDemo.java

---------------------------------------    
    L:用自定義類來模拟LineNumberReader的特有功能getLineNumber()和setLineNumber()
        LineNumberReader類的特有功能:
            public int getLineNumber() 擷取目前行号
            public void setLineNumber(int lineNumber) 設定目前行号
            
        一般來說,如果某個類裡面有getXxx()和SetXxx()方法,那麼該類的成員變量一定有個Xxx的成員變量。
        
        方式一:
      
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_09;
 2 
 3 import java.io.IOException;
 4 import java.io.Reader;
 5 
 6 public class MyLineNumberReader {
 7     private Reader r;
 8     private int lineNumber = 0;
 9 
10     public MyLineNumberReader(Reader r) {
11         this.r = r;
12     }
13 
14     public int getLineNumber() {
15         return lineNumber;
16     }
17 
18     public void setLineNumber(int lineNumber) {
19         this.lineNumber = lineNumber;
20     }
21 
22     public String readLine() throws IOException {
23         lineNumber++; // 每調用一次readLine()方法後就讓行号自加1
24 
25         StringBuilder sb = new StringBuilder();
26 
27         int ch = 0;
28         while ((ch = r.read()) != -1) {
29             if (ch == '\r') {
30                 continue;
31             }
32 
33             if (ch == '\n') {
34                 return sb.toString();
35             } else {
36                 sb.append((char) ch);
37             }
38         }
39 
40         if (sb.length() > 0) {
41             return sb.toString();
42         }
43 
44         return null;
45     }
46 
47     public void close() throws IOException {
48         this.r.close();
49     }
50 }      

MyLineNumberReader.java

java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_09;
 2 
 3 import java.io.FileReader;
 4 import java.io.IOException;
 5 
 6 public class MyLineNumberReaderTest {
 7     public static void main(String[] args) throws IOException {
 8         MyLineNumberReader mlnr = new MyLineNumberReader(new FileReader("my.txt"));
 9         
10         mlnr.setLineNumber(10);
11 
12         String line = null;
13         while ((line = mlnr.readLine()) != null) {
14             System.out.println(mlnr.getLineNumber() + ":" + line);
15         }
16 
17         mlnr.close();
18 
19     }
20 }      

MyLineNumberReaderTest.java

方式二:
      
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_08;
 2 
 3 import java.io.IOException;
 4 import java.io.Reader;
 5 
 6 /*
 7  * 用Reader來模拟BufferedReader的readLine()功能
 8  * 
 9  * readLine() 一次讀取一行,根據換行符判斷是否結束,隻傳回内容,不傳回換行符。
10  * 
11  *
12  * 思考:寫一個方法,傳回值是一個字元串。
13  * 
14  * 我要傳回一個字元串,我該怎麼辦呢? 
15  * 因為我們現在有一個Reader對象,是以我們必須去看看r對象能夠讀取什麼東西呢? 
16  * r對象有兩個讀取方法:一次讀取一個字元或者一次讀取一個字元數組。
17  * 
18  * 那麼,我們要傳回一個字元串,用哪個方法比較好呢? 
19  * 我們很容易想到用字元數組比較好,但是問題來了,就是這個字元數組的長度是多長呢?
20  * 根本就沒有辦法定義數組的長度,你定義多長都不合适。 是以,隻能選擇一次讀取一個字元。
21  * 
22  * 但是呢,用這種方式的時候,我們在讀取下一個字元的時候,上一個字元就丢失了。
23  * 是以,我們又應該定義一個臨時存儲空間把讀取過的字元給存儲起來。
24  * 
25  * 這個用誰比較合适呢?
26  * 數組、集合、字元串緩沖區三個可供選擇。
27  * 經過簡單的分析,最終選擇使用字元串緩沖區對象。并且使用的是StringBuilder。
28  * 
29  */
30 public class MyBufferedReader {
31     private Reader r;
32 
33     public MyBufferedReader(Reader r) {
34         this.r = r;
35     }
36     
37     public String readLine() throws IOException {
38         StringBuilder sb = new StringBuilder();
39         
40         // 做這個讀取最麻煩的是判斷結束,但是在結束之前應該是一直讀取,直到-1。
41         int ch = 0;
42         while ((ch = r.read()) != -1) { 
43             if (ch == '\r') {
44                 continue;
45             }
46 
47             if (ch == '\n') {
48                 return sb.toString(); 
49             } else {
50                 sb.append((char)ch); 
51             }
52         }
53 
54         // 如果原始資料最後一行沒有回車換行符(\r\n),讀取到的最好一行資料會丢失,是以判斷讀取到的最後一行的sb的長度,長度大于0說明有資料。
55         if (sb.length() > 0) {
56             return sb.toString();
57         }
58 
59         return null;
60     }
61 
62     /*
63      * 先寫一個關閉流的方法
64      */
65     public void close() throws IOException {
66         this.r.close();
67     }
68 }      
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_09;
 2 
 3 import java.io.IOException;
 4 import java.io.Reader;
 5 
 6 import cn.itcast_08.MyBufferedReader;
 7 
 8 public class MyLineNumberReader2 extends MyBufferedReader {
 9     private Reader r;
10 
11     private int lineNumber = 0;
12 
13     public MyLineNumberReader2(Reader r) {
14         super(r);
15     }
16 
17     public int getLineNumber() {
18         return lineNumber;
19     }
20 
21     public void setLineNumber(int lineNumber) {
22         this.lineNumber = lineNumber;
23     }
24     
25     // 重寫父類MyBufferedReader的readLine()方法
26     @Override
27     public String readLine() throws IOException {
28         lineNumber++;
29         return super.readLine();
30     }
31 }      

MyLineNumberReader2.java

java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
java基礎學習_IO流03_字元流、IO流小結、案例_day21總結
1 package cn.itcast_09;
 2 
 3 import java.io.FileReader;
 4 import java.io.IOException;
 5 
 6 public class MyLineNumberReaderTest2 {
 7     public static void main(String[] args) throws IOException {
 8         // 改進版
 9         MyLineNumberReader2 mlnr2 = new MyLineNumberReader2(new FileReader("my.txt"));
10         
11         mlnr2.setLineNumber(10);
12 
13         String line = null;
14         while ((line = mlnr2.readLine()) != null) {
15             System.out.println(mlnr2.getLineNumber() + ":" + line);
16         }
17 
18         mlnr2.close();
19 
20 
21     }
22 }      

MyLineNumberReaderTest2.java

=============================================================================      

我的GitHub位址:

https://github.com/heizemingjun

我的部落格園位址:

http://www.cnblogs.com/chenmingjun

我的螞蟻筆記部落格位址:

http://blog.leanote.com/chenmingjun

Copyright ©2018 黑澤明軍

【轉載文章務必保留出處和署名,謝謝!】