天天看點

Java基礎學習第二十二天——轉換流之字元流應用

文檔版本 開發工具 測試平台 工程名字 日期 作者 備注
V1.0 2016.03.22 lutianfei none
V1.1 2016.05.17 lutianfei 複習與整理
    • 轉換流
      • 轉換流出現的原因及思想
      • 編碼表
        • 常見編碼表
        • 字元串中的編碼問題
      • 轉換流概述
        • OutputStreamWriter寫資料
          • 字元流操作要注意的問題
          • InputStreamReader讀資料
          • 字元流複制文本檔案
      • 轉換流的簡化寫法
        • 字元緩沖流
          • BufferedWriter字元緩沖輸出流
          • BufferedReader
        • 字元緩沖流的特殊方法
      • IO流小結
        • IO流練習

轉換流

轉換流出現的原因及思想

  • 由于位元組流操作中文不是特别友善,是以,java就提供了

    轉換流

  • 字元流

    =

    位元組流

    +

    編碼表

編碼表

  • 由字元及其對應的數值組成的一張表

常見編碼表

  • 計算機隻能識别二進制資料,早期由來是電信号。為了友善應用計算機,讓它可以識别各個國家的文字。
  • ASCII:美國标準資訊交換碼。
    • 用一個位元組的7位可以表示。
  • ISO8859-1:拉丁碼表。歐洲碼表
    • 用一個位元組的8位表示。
  • GB2312:中國的中文編碼表。
  • GBK:中國的中文編碼表更新,融合了更多的中文文字元号。
  • GB18030:GBK的取代版本
  • BIG-5碼 :通行于台灣、香港地區的一個繁體字編碼方案,俗稱“大五碼”。
  • Unicode:國際标準碼,融合了多種文字。
    • 所有文字都用兩個位元組來表示,Java語言使用的就是unicode
  • UTF-8

    :最多用三個位元組來表示一個字元。
  • UTF-8不同,它定義了一種“區間規則”,這種規則可以和ASCII編碼保持最大程度的相容:
    • 它将Unicode編碼為00000000-000000**7F**的字元,用單個位元組來表示
    • 它将Unicode編碼為00000080-00000**7FF**的字元用兩個位元組表示
    • 它将Unicode編碼為00000800-0000**FFFF**的字元用3位元組表示

字元串中的編碼問題

  • 編碼
    • byte[]

      getBytes

      (String charsetName):使用指定的字元集合把字元串編碼為位元組數組
  • 解碼
    • String(byte[] bytes, String charsetName):通過指定的字元集解碼位元組數組
  • 編碼:把看得懂的變成看不懂的
    • String – byte[]
  • 解碼:把看不懂的變成看得懂的
    • byte[] – String
public class StringDemo {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String s = "你好";

        // String -- byte[]
        byte[] bys = s.getBytes(); // [-60, -29, -70, -61]
        // byte[] bys = s.getBytes("GBK");// [-60, -29, -70, -61]
        // byte[] bys = s.getBytes("UTF-8");// [-28, -67, -96, -27, -91, -67]
        System.out.println(Arrays.toString(bys));

        // byte[] -- String
        String ss = new String(bys); // 你好
        // String ss = new String(bys, "GBK"); // 你好
        // String ss = new String(bys, "UTF-8"); // ???
        System.out.println(ss);
    }
}
           

轉換流概述

  • OutputStreamWriter 字元輸出流
    • OutputStreamWriter

      (OutputStream out):根據預設編碼把位元組流的資料轉換為字元流
    • OutputStreamWriter

      (OutputStream out,String charsetName):根據指定編碼把位元組流資料轉換為字元流
  • InputStreamReader 字元輸入流
    • InputStreamReader(InputStream is):用預設的編碼讀取資料
    • InputStreamReader(InputStream is,String charsetName):用指定的編碼讀取資料

OutputStreamWriter寫資料

  • 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):寫一個字元串的一部分
public class OutputStreamWriterDemo {
    public static void main(String[] args) throws IOException {
        // 建立對象
        // OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
        // "osw.txt")); // 預設GBK
        // OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
        // "osw.txt"), "GBK"); // 指定GBK
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
                "osw.txt"), "UTF-8"); // 指定UTF-8
        // 寫資料
        osw.write("中國");

        // 釋放資源
        osw.close();
    }
}
           
字元流操作要注意的問題
  • flush()

    close()

    的差別
    • A:close()關閉流對象,但是先重新整理一次緩沖區。關閉之後,流對象不可以繼續再使用了。
    • B:flush()僅僅重新整理緩沖區,重新整理之後,流對象還可以繼續使用。
public class OutputStreamWriterDemo {
    public static void main(String[] args) throws IOException {
        // 建立對象
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("osw2.txt"));

        // 寫資料
        // public void write(int c):寫一個字元
        // osw.write('a');
        // osw.write(97);
        // 為什麼資料沒有進去呢?
        // 原因是:字元 = 2位元組
        // 檔案中資料存儲的基本機關是位元組。
        // void flush()

        // public void write(char[] cbuf):寫一個字元數組
        // char[] chs = {'a','b','c','d','e'};
        // osw.write(chs);

        // public void write(char[] cbuf,int off,int len):寫一個字元數組的一部分
        // osw.write(chs,1,3);

        // public void write(String str):寫一個字元串
        // osw.write("我愛林青霞");

        // public void write(String str,int off,int len):寫一個字元串的一部分
        osw.write("我愛林青霞", , );

        // 重新整理緩沖區
        osw.flush();
        // osw.write("我愛林青霞", 2, 3);

        // 釋放資源
        osw.close();
        // java.io.IOException: Stream closed
        // osw.write("我愛林青霞", 2, 3);
    }
}
           
InputStreamReader讀資料
  • 讀資料方法
    • int read():一次讀取一個字元
    • int read(char[] chs):一次讀取一個字元數組
public class InputStreamReaderDemo {
    public static void main(String[] args) throws IOException {
        // 建立對象
        // InputStreamReader isr = new InputStreamReader(new FileInputStream(
        // "osw.txt"));

        // InputStreamReader isr = new InputStreamReader(new FileInputStream(
        // "osw.txt"), "GBK");

        InputStreamReader isr = new InputStreamReader(new FileInputStream("osw.txt"), "UTF-8");

        // 讀取資料
        // 一次讀取一個字元
        int ch = ;
        while ((ch = isr.read()) != -) {
            System.out.print((char) ch);
        }

        // 釋放資源
        isr.close();
    }
}
           
public class InputStreamReaderDemo {
    public static void main(String[] args) throws IOException {
        // 建立對象
        InputStreamReader isr = new InputStreamReader(new FileInputStream(
                "StringDemo.java"));

        // 一次讀取一個字元
        // int ch = 0;
        // while ((ch = isr.read()) != -1) {
        // System.out.print((char) ch);
        // }

        // 一次讀取一個字元數組
        char[] chs = new char[];
        int len = ;
        while ((len = isr.read(chs)) != -) {
            System.out.print(new String(chs, , len));
        }

        // 釋放資源
        isr.close();
    }
}
           
字元流複制文本檔案
  • 把目前項目目錄下的a.txt内容複制到目前項目目錄下的b.txt中
/*
 * 需求:把目前項目目錄下的a.txt内容複制到目前項目目錄下的b.txt中
 * 
 * 資料源:
 *         a.txt -- 讀取資料 -- 字元轉換流 -- InputStreamReader
 * 目的地:
 *         b.txt -- 寫出資料 -- 字元轉換流 -- OutputStreamWriter
 */
public class CopyFileDemo {
    public static void main(String[] args) throws IOException {
        // 封裝資料源
        InputStreamReader isr = new InputStreamReader(new FileInputStream(
                "a.txt"));
        // 封裝目的地
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
                "b.txt"));

        // 讀寫資料
        // 方式1
        // int ch = 0;
        // while ((ch = isr.read()) != -1) {
        // osw.write(ch);
        // }

        // 方式2
        char[] chs = new char[];
        int len = ;
        while ((len = isr.read(chs)) != -) {
            osw.write(chs, , len);
            // osw.flush();
        }

        // 釋放資源
        osw.close();
        isr.close();
    }
}
           
  • 把c:\a.txt内容複制到d:\b.txt中

轉換流的簡化寫法

  • 轉換流的名字比較長,而我們常見的操作都是按照本地預設編碼實作的,是以,為了簡化我們的書寫,轉換流提供了對應的子類。
  • FileWriter

    :寫資料
  • FileReader

    :讀取資料
  • OutputStreamWriter = FileOutputStream + 編碼表(GBK)
    • FileWriter = FileOutputStream + 編碼表(GBK)
  • InputStreamReader = FileInputStream + 編碼表(GBK)
    • FileReader = FileInputStream + 編碼表(GBK)
/*
 * 由于我們常見的操作都是使用本地預設編碼,是以,不用指定編碼。
 * 而轉換流的名稱有點長,是以,Java就提供了其子類供我們使用。
 * OutputStreamWriter = FileOutputStream + 編碼表(GBK)

 * 需求:把目前項目目錄下的a.txt内容複制到目前項目目錄下的b.txt中
 * 
 * 資料源:
 *         a.txt -- 讀取資料 -- 字元轉換流 -- InputStreamReader -- FileReader
 * 目的地:
 *         b.txt -- 寫出資料 -- 字元轉換流 -- OutputStreamWriter -- FileWriter
 */
public class CopyFileDemo2 {
    public static void main(String[] args) throws IOException {
        // 封裝資料源
        FileReader fr = new FileReader("a.txt");
        // 封裝目的地
        FileWriter fw = new FileWriter("b.txt");

        // 一次一個字元
        // int ch = 0;
        // while ((ch = fr.read()) != -1) {
        // fw.write(ch);
        // }

        // 一次一個字元數組
        char[] chs = new char[];
        int len = ;
        while ((len = fr.read(chs)) != -) {
            fw.write(chs, , len);
            fw.flush();
        }

        // 釋放資源
        fw.close();
        fr.close();
    }
}
           

字元緩沖流

  • 字元流為了高效讀寫,也提供了對應的字元緩沖流。
    • BufferedWriter:字元緩沖輸出流
    • BufferedReader:字元緩沖輸入流
BufferedWriter:字元緩沖輸出流
  • 将文本寫入字元輸出流,緩沖各個字元,進而提供單個字元、數組和字元串的高效寫入。
  • 可以指定緩沖區的大小,或者接受預設的大小。在大多數情況下,預設值就足夠大了。
public class BufferedWriterDemo {
    public static void main(String[] args) throws IOException {
        // BufferedWriter(Writer out)
        // BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
        // new FileOutputStream("bw.txt")));

        BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));

        bw.write("hello");
        bw.write("world");
        bw.write("java");
        bw.flush();

        bw.close();
    }
}
           
BufferedReader
  • 從字元輸入流中讀取文本,緩沖各個字元,進而實作字元、數組和行的高效讀取。
  • 可以指定緩沖區的大小,或者可使用預設的大小。大多數情況下,預設值就足夠大了。
public class BufferedReaderDemo {
    public static void main(String[] args) throws IOException {
        // 建立字元緩沖輸入流對象
        BufferedReader br = new BufferedReader(new FileReader("bw.txt"));

        // 方式1
        // int ch = 0;
        // while ((ch = br.read()) != -1) {
        // System.out.print((char) ch);
        // }

        // 方式2
        char[] chs = new char[];
        int len = ;
        while ((len = br.read(chs)) != -) {
            System.out.print(new String(chs, , len));
        }

        // 釋放資源
        br.close();
    }
}
           
  • 文本複制例子
/*
 * 需求:把目前項目目錄下的a.txt内容複制到目前項目目錄下的b.txt中
 * 
 * 資料源:
 *         a.txt -- 讀取資料 -- 字元轉換流 -- InputStreamReader -- FileReader -- BufferedReader
 * 目的地:
 *         b.txt -- 寫出資料 -- 字元轉換流 -- OutputStreamWriter -- FileWriter -- BufferedWriter
 */
public class CopyFileDemo {
    public static void main(String[] args) throws IOException {
        // 封裝資料源
        BufferedReader br = new BufferedReader(new FileReader("a.txt"));
        // 封裝目的地
        BufferedWriter bw = new BufferedWriter(new FileWriter("b.txt"));

        // 兩種方式其中的一種一次讀寫一個字元數組
        char[] chs = new char[];
        int len = ;
        while ((len = br.read(chs)) != -) {
            bw.write(chs, , len);
            bw.flush();
        }

        // 釋放資源
        bw.close();
        br.close();
    }
}
           

字元緩沖流的特殊方法

  • BufferedWriter:
    • public void newLine():根據系統來決定換行符
  • BufferedReader:
    • public String readLine():一次讀取一行資料
      • 包含該行内容的字元串,不包含任何行終止符,如果已到達流末尾,則傳回

        null

public class BufferedDemo {
    public static void main(String[] args) throws IOException {
        // write();
        read();
    }

    private static void read() throws IOException {
        // 建立字元緩沖輸入流對象
        BufferedReader br = new BufferedReader(new FileReader("bw2.txt"));

        // 最終版代碼
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

        //釋放資源
        br.close();
    }

    private static void write() throws IOException {
        // 建立字元緩沖輸出流對象
        BufferedWriter bw = new BufferedWriter(new FileWriter("bw2.txt"));
        for (int x = ; x < ; x++) {
            bw.write("hello" + x);
            // bw.write("\r\n");
            bw.newLine();
            bw.flush();
        }
        bw.close();
    }

}
           
  • 字元緩沖流特殊功能複制文本檔案(必會)
/*
 * 需求:把目前項目目錄下的a.txt内容複制到目前項目目錄下的b.txt中
 * 
 * 資料源:
 *         a.txt -- 讀取資料 -- 字元轉換流 -- InputStreamReader -- FileReader -- BufferedReader
 * 目的地:
 *         b.txt -- 寫出資料 -- 字元轉換流 -- OutputStreamWriter -- FileWriter -- BufferedWriter
 */
public class CopyFileDemo2 {
    public static void main(String[] args) throws IOException {
        // 封裝資料源
        BufferedReader br = new BufferedReader(new FileReader("a.txt"));
        // 封裝目的地
        BufferedWriter bw = new BufferedWriter(new FileWriter("b.txt"));

        // 讀寫資料
        String line = null;
        while ((line = br.readLine()) != null) {
            bw.write(line);
            bw.newLine();
            bw.flush();
        }

        // 釋放資源
        bw.close();
        br.close();
    }
}
           

IO流小結

Java基礎學習第二十二天——轉換流之字元流應用

IO流練習

  • 複制文本檔案
/*
 * 複制文本檔案
 * 
 * 分析:
 *         而字元流有5種方式,是以做這個題目我們有5種方式。推薦掌握第5種。
 * 資料源:
 *         c:\\a.txt -- FileReader -- BufferdReader
 * 目的地:
 *         d:\\b.txt -- FileWriter -- BufferedWriter
 */
public class CopyFileDemo {
    public static void main(String[] args) throws IOException {
        String srcString = "c:\\a.txt";
        String destString = "d:\\b.txt";
        // method1(srcString, destString);
        // method2(srcString, destString);
        // method3(srcString, destString);
        // method4(srcString, destString);
        method5(srcString, destString);
    }

    // 字元緩沖流一次讀寫一個字元串
    private static void method5(String srcString, String destString)
            throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(srcString));
        BufferedWriter bw = new BufferedWriter(new FileWriter(destString));

        String line = null;
        while ((line = br.readLine()) != null) {
            bw.write(line);
            bw.newLine();
            bw.flush();
        }

        bw.close();
        br.close();
    }

    // 字元緩沖流一次讀寫一個字元數組
    private static void method4(String srcString, String destString)
            throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(srcString));
        BufferedWriter bw = new BufferedWriter(new FileWriter(destString));

        char[] chs = new char[];
        int len = ;
        while ((len = br.read(chs)) != -) {
            bw.write(chs, , len);
        }

        bw.close();
        br.close();
    }

    // 字元緩沖流一次讀寫一個字元
    private static void method3(String srcString, String destString)
            throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(srcString));
        BufferedWriter bw = new BufferedWriter(new FileWriter(destString));

        int ch = ;
        while ((ch = br.read()) != -) {
            bw.write(ch);
        }

        bw.close();
        br.close();
    }

    // 基本字元流一次讀寫一個字元數組
    private static void method2(String srcString, String destString)
            throws IOException {
        FileReader fr = new FileReader(srcString);
        FileWriter fw = new FileWriter(destString);

        char[] chs = new char[];
        int len = ;
        while ((len = fr.read(chs)) != -) {
            fw.write(chs, , len);
        }

        fw.close();
        fr.close();
    }

    // 基本字元流一次讀寫一個字元
    private static void method1(String srcString, String destString)
            throws IOException {
        FileReader fr = new FileReader(srcString);
        FileWriter fw = new FileWriter(destString);

        int ch = ;
        while ((ch = fr.read()) != -) {
            fw.write(ch);
        }

        fw.close();
        fr.close();
    }
}
           
  • 複制圖檔
/*
 * 複制圖檔
 * 
 * 分析:
 *         複制資料,如果我們知道用記事本打開并能夠讀懂,就用字元流,否則用位元組流。
 *         通過該原理,我們知道我們應該采用位元組流。
 *         而位元組流有4種方式,是以做這個題目我們有4種方式。推薦掌握第4種。
 * 
 * 資料源:
 *         c:\\a.jpg -- FileInputStream -- BufferedInputStream
 * 目的地:
 *         d:\\b.jpg -- FileOutputStream -- BufferedOutputStream
 */
public class CopyImageDemo {
    public static void main(String[] args) throws IOException {
        // 使用字元串作為路徑
        // String srcString = "c:\\a.jpg";
        // String destString = "d:\\b.jpg";
        // 使用File對象做為參數
        File srcFile = new File("c:\\a.jpg");
        File destFile = new File("d:\\b.jpg");

        // method1(srcFile, destFile);
        // method2(srcFile, destFile);
        // method3(srcFile, destFile);
        method4(srcFile, destFile);
    }

    // 位元組緩沖流一次讀寫一個位元組數組
    private static void method4(File srcFile, File destFile) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                srcFile));
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(destFile));

        byte[] bys = new byte[];
        int len = ;
        while ((len = bis.read(bys)) != -) {
            bos.write(bys, , len);
        }

        bos.close();
        bis.close();
    }

    // 位元組緩沖流一次讀寫一個位元組
    private static void method3(File srcFile, File destFile) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                srcFile));
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(destFile));

        int by = ;
        while ((by = bis.read()) != -) {
            bos.write(by);
        }

        bos.close();
        bis.close();
    }

    // 基本位元組流一次讀寫一個位元組數組
    private static void method2(File srcFile, File destFile) throws IOException {
        FileInputStream fis = new FileInputStream(srcFile);
        FileOutputStream fos = new FileOutputStream(destFile);

        byte[] bys = new byte[];
        int len = ;
        while ((len = fis.read(bys)) != -) {
            fos.write(bys, , len);
        }

        fos.close();
        fis.close();
    }

    // 基本位元組流一次讀寫一個位元組
    private static void method1(File srcFile, File destFile) throws IOException {
        FileInputStream fis = new FileInputStream(srcFile);
        FileOutputStream fos = new FileOutputStream(destFile);

        int by = ;
        while ((by = fis.read()) != -) {
            fos.write(by);
        }

        fos.close();
        fis.close();
    }
}
           
  • 把ArrayList集合中的字元串資料存儲到文本檔案
/*
 * 需求:把ArrayList集合中的字元串資料存儲到文本檔案
 * 
 * 分析:
 * 通過題目的意思我們可以知道如下的一些内容,
 * ArrayList集合裡存儲的是字元串。
 * 周遊ArrayList集合,把資料擷取到。
 * 然後存儲到文本檔案中。
 * 文本檔案說明使用字元流。
 * 
 * 資料源:
 *         ArrayList<String> -- 周遊得到每一個字元串資料
 * 目的地:
 *         a.txt -- FileWriter -- BufferedWriter
 */
public class ArrayListToFileDemo {
    public static void main(String[] args) throws IOException {
        // 封裝資料源(建立集合對象)
        ArrayList<String> array = new ArrayList<String>();
        array.add("hello");
        array.add("world");
        array.add("java");

        // 封裝目的地
        BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));

        // 周遊集合
        for (String s : array) {
            // 寫資料
            bw.write(s);
            bw.newLine();
            bw.flush();
        }

        // 釋放資源
        bw.close();
    }
}
           
  • 從文本檔案中讀取資料(每一行為一個字元串資料)到集合中,并周遊集合
/*
 * 需求:從文本檔案中讀取資料(每一行為一個字元串資料)到集合中,并周遊集合
 * 
 * 分析:
 *         通過題目的意思我們可以知道如下的一些内容,
 *             資料源是一個文本檔案。
 *             目的地是一個集合。
 *             而且元素是字元串。
 * 
 * 資料源:
 *         b.txt -- FileReader -- BufferedReader
 * 目的地:
 *         ArrayList<String>
 */
public class FileToArrayListDemo {
    public static void main(String[] args) throws IOException {
        // 封裝資料源
        BufferedReader br = new BufferedReader(new FileReader("b.txt"));
        // 封裝目的地(建立集合對象)
        ArrayList<String> array = new ArrayList<String>();

        // 讀取資料存儲到集合中
        String line = null;
        while ((line = br.readLine()) != null) {
            array.add(line);
        }

        // 釋放資源
        br.close();

        // 周遊集合
        for (String s : array) {
            System.out.println(s);
        }
    }
}
           
  • 随機擷取文本中的名字
/*
 * 需求:我有一個文本檔案中存儲了幾個名稱,請大家寫一個程式實作随機擷取一個人的名字。
 * 
 * 分析:
 *         A:把文本檔案中的資料存儲到集合中
 *         B:随機産生一個索引
 *         C:根據該索引擷取一個值
 */
public class GetName {
    public static void main(String[] args) throws IOException {
        // 把文本檔案中的資料存儲到集合中
        BufferedReader br = new BufferedReader(new FileReader("b.txt"));
        ArrayList<String> array = new ArrayList<String>();
        String line = null;
        while ((line = br.readLine()) != null) {
            array.add(line);
        }
        br.close();

        // 随機産生一個索引
        Random r = new Random();
        int index = r.nextInt(array.size());

        // 根據該索引擷取一個值
        String name = array.get(index);
        System.out.println("該幸運者是:" + name);
    }
}
           
  • 複制單極檔案夾
/*
 * 需求:複制單極檔案夾
 * 
 * 資料源:e:\\demo
 * 目的地:e:\\test
 * 
 * 分析:
 *         A:封裝目錄
 *         B:擷取該目錄下的所有文本的File數組
 *         C:周遊該File數組,得到每一個File對象
 *         D:把該File進行複制
 */
public class CopyFolderDemo {
    public static void main(String[] args) throws IOException {
        // 封裝目錄
        File srcFolder = new File("e:\\demo");
        // 封裝目的地
        File destFolder = new File("e:\\test");
        // 如果目的地檔案夾不存在,就建立
        if (!destFolder.exists()) {
            destFolder.mkdir();
        }

        // 擷取該目錄下的所有文本的File數組
        File[] fileArray = srcFolder.listFiles();

        // 周遊該File數組,得到每一個File對象
        for (File file : fileArray) {
            // System.out.println(file);
            // 資料源:e:\\demo\\e.mp3
            // 目的地:e:\\test\\e.mp3
            String name = file.getName(); // e.mp3
            File newFile = new File(destFolder, name); // e:\\test\\e.mp3

            copyFile(file, newFile);
        }
    }

    private static void copyFile(File file, File newFile) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                file));
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(newFile));

        byte[] bys = new byte[];
        int len = ;
        while ((len = bis.read(bys)) != -) {
            bos.write(bys, , len);
        }

        bos.close();
        bis.close();
    }
}
           
  • 複制單極檔案夾中指定檔案并修改檔案名稱
/*
 * 需求:複制指定目錄下的指定檔案,并修改字尾名。
 * 指定的檔案是:.java檔案。
 * 指定的字尾名是:.jad
 * 指定的目錄是:jad
 * 
 * 資料源:e:\\java\\A.java
 * 目的地:e:\\jad\\A.jad
 * 
 * 分析:
 *         A:封裝目錄
 *         B:擷取該目錄下的java檔案的File數組
 *         C:周遊該File數組,得到每一個File對象
 *         D:把該File進行複制
 *         E:在目的地目錄下改名
 */
public class CopyFolderDemo {
    public static void main(String[] args) throws IOException {
        // 封裝目錄
        File srcFolder = new File("e:\\java");
        // 封裝目的地
        File destFolder = new File("e:\\jad");
        // 如果目的地目錄不存在,就建立
        if (!destFolder.exists()) {
            destFolder.mkdir();
        }

        // 擷取該目錄下的java檔案的File數組
        File[] fileArray = srcFolder.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return new File(dir, name).isFile() && name.endsWith(".java");
            }
        });

        // 周遊該File數組,得到每一個File對象
        for (File file : fileArray) {
            // System.out.println(file);
            // 資料源:e:\java\DataTypeDemo.java
            // 目的地:e:\\jad\DataTypeDemo.java
            String name = file.getName();
            File newFile = new File(destFolder, name);
            copyFile(file, newFile);
        }

        // 在目的地目錄下改名
        File[] destFileArray = destFolder.listFiles();
        for (File destFile : destFileArray) {
            // System.out.println(destFile);
            // e:\jad\DataTypeDemo.java
            // e:\\jad\\DataTypeDemo.jad
            String name =destFile.getName(); //DataTypeDemo.java
            String newName = name.replace(".java", ".jad");//DataTypeDemo.jad

            File newFile = new File(destFolder,newName);
            destFile.renameTo(newFile);
        }
    }

    private static void copyFile(File file, File newFile) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                file));
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(newFile));

        byte[] bys = new byte[];
        int len = ;
        while ((len = bis.read(bys)) != -) {
            bos.write(bys, , len);
        }

        bos.close();
        bis.close();
    }
}
           
  • 複制多極檔案夾
/*
 * 需求:複制多極檔案夾
 * 
 * 資料源:E:\JavaSE\day21\code\demos
 * 目的地:E:\\
 * 
 * 分析:
 *         A:封裝資料源File
 *         B:封裝目的地File
 *         C:判斷該File是檔案夾還是檔案
 *             a:是檔案夾
 *                 就在目的地目錄下建立該檔案夾
 *                 擷取該File對象下的所有檔案或者檔案夾File對象
 *                 周遊得到每一個File對象
 *                 回到C
 *             b:是檔案
 *                 就複制(位元組流)
 */
public class CopyFoldersDemo {
    public static void main(String[] args) throws IOException {
        // 封裝資料源File
        File srcFile = new File("E:\\JavaSE\\day21\\code\\demos");
        // 封裝目的地File
        File destFile = new File("E:\\");

        // 複制檔案夾的功能
        copyFolder(srcFile, destFile);
    }

    private static void copyFolder(File srcFile, File destFile)
            throws IOException {
        // 判斷該File是檔案夾還是檔案
        if (srcFile.isDirectory()) {
            // 檔案夾
            File newFolder = new File(destFile, srcFile.getName());
            newFolder.mkdir();

            // 擷取該File對象下的所有檔案或者檔案夾File對象
            File[] fileArray = srcFile.listFiles();
            for (File file : fileArray) {
                copyFolder(file, newFolder);
            }
        } else {
            // 檔案
            File newFile = new File(destFile, srcFile.getName());
            copyFile(srcFile, newFile);
        }
    }

    private static void copyFile(File srcFile, File newFile) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
                srcFile));
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(newFile));

        byte[] bys = new byte[];
        int len = ;
        while ((len = bis.read(bys)) != -) {
            bos.write(bys, , len);
        }

        bos.close();
        bis.close();
    }
}
           
  • 鍵盤錄入5個學生資訊(姓名,國文成績,數學成績,英語成績),按照總分從高到低存入文本檔案
/*
 * 鍵盤錄入5個學生資訊(姓名,國文成績,數學成績,英語成績),按照總分從高到低存入文本檔案
 * 
 * 分析:
 *         A:建立學生類
 *         B:建立集合對象
 *             TreeSet<Student>
 *         C:鍵盤錄入學生資訊存儲到集合
 *         D:周遊集合,把資料寫到文本檔案
 */
public class StudentDemo {
    public static void main(String[] args) throws IOException {
        // 建立集合對象
        TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                int num = s2.getSum() - s1.getSum();
                int num2 = num ==  ? s1.getChinese() - s2.getChinese() : num;
                int num3 = num2 ==  ? s1.getMath() - s2.getMath() : num2;
                int num4 = num3 ==  ? s1.getEnglish() - s2.getEnglish() : num3;
                int num5 = num4 ==  ? s1.getName().compareTo(s2.getName())
                        : num4;
                return num5;
            }
        });

        // 鍵盤錄入學生資訊存儲到集合
        for (int x = ; x <= ; x++) {
            Scanner sc = new Scanner(System.in);
            System.out.println("請錄入第" + x + "個的學習資訊");
            System.out.println("姓名:");
            String name = sc.nextLine();
            System.out.println("國文成績:");
            int chinese = sc.nextInt();
            System.out.println("數學成績:");
            int math = sc.nextInt();
            System.out.println("英語成績:");
            int english = sc.nextInt();

            // 建立學生對象
            Student s = new Student();
            s.setName(name);
            s.setChinese(chinese);
            s.setMath(math);
            s.setEnglish(english);

            // 把學生資訊添加到集合
            ts.add(s);
        }

        // 周遊集合,把資料寫到文本檔案
        BufferedWriter bw = new BufferedWriter(new FileWriter("students.txt"));
        bw.write("學生資訊如下:");
        bw.newLine();
        bw.flush();
        bw.write("姓名,國文成績,數學成績,英語成績");
        bw.newLine();
        bw.flush();
        for (Student s : ts) {
            StringBuilder sb = new StringBuilder();
            sb.append(s.getName()).append(",").append(s.getChinese())
                    .append(",").append(s.getMath()).append(",")
                    .append(s.getEnglish());
            bw.write(sb.toString());
            bw.newLine();
            bw.flush();
        }
        // 釋放資源
        bw.close();
        System.out.println("學習資訊存儲完畢");
    }
}
           
  • 已知s.txt檔案中有這樣的一個字元串:“hcexfgijkamdnoqrzstuvwybpl”
    • 請編寫程式讀取資料内容,把資料排序後寫入ss.txt中。
/*
 * 已知s.txt檔案中有這樣的一個字元串:“hcexfgijkamdnoqrzstuvwybpl”
 * 請編寫程式讀取資料内容,把資料排序後寫入ss.txt中。
 * 
 * 分析:
 *         A:把s.txt這個檔案給做出來
 *         B:讀取該檔案的内容,存儲到一個字元串中
 *         C:把字元串轉換為字元數組
 *         D:對字元數組進行排序
 *         E:把排序後的字元數組轉換為字元串
 *         F:把字元串再次寫入ss.txt中
 */
public class StringDemo {
    public static void main(String[] args) throws IOException {
        // 讀取該檔案的内容,存儲到一個字元串中
        BufferedReader br = new BufferedReader(new FileReader("s.txt"));
        String line = br.readLine();
        br.close();

        // 把字元串轉換為字元數組
        char[] chs = line.toCharArray();

        // 對字元數組進行排序
        Arrays.sort(chs);

        // 把排序後的字元數組轉換為字元串
        String s = new String(chs);

        // 把字元串再次寫入ss.txt中
        BufferedWriter bw = new BufferedWriter(new FileWriter("ss.txt"));
        bw.write(s);
        bw.newLine();
        bw.flush();

        bw.close();
    }
}
           
  • 用Reader模拟BufferedReader的readLine()功能
/*
 * 用Reader模拟BufferedReader的readLine()功能
 * 
 * readLine():一次讀取一行,根據換行符判斷是否結束,隻傳回内容,不傳回換行符
 */
public class MyBufferedReader {
    private Reader r;

    public MyBufferedReader(Reader r) {
        this.r = r;
    }

    /*
     * 思考:寫一個方法,傳回值是一個字元串。
     */
    public String readLine() throws IOException {
        /*
         * 我要傳回一個字元串,我該怎麼辦呢? 我們必須去看看r對象能夠讀取什麼東西呢? 兩個讀取方法,一次讀取一個字元或者一次讀取一個字元數組
         * 那麼,我們要傳回一個字元串,用哪個方法比較好呢? 我們很容易想到字元數組比較好,但是問題來了,就是這個數組的長度是多長呢?
         * 根本就沒有辦法定義數組的長度,你定義多長都不合适。 是以,隻能選擇一次讀取一個字元。
         * 但是呢,這種方式的時候,我們再讀取下一個字元的時候,上一個字元就丢失了 是以,我們又應該定義一個臨時存儲空間把讀取過的字元給存儲起來。
         * 這個用誰比較合适呢?數組,集合,字元串緩沖區三個可供選擇。
         * 經過簡單的分析,最終選擇使用字元串緩沖區對象。并且使用的是StringBuilder
         */
        StringBuilder sb = new StringBuilder();

        // 做這個讀取最麻煩的是判斷結束,但是在結束之前應該是一直讀取,直到-1


        /*
        hello
        world
        java    

        104101108108111
        119111114108100
        1069711897
         */

        int ch = ;
        while ((ch = r.read()) != -) { //104,101,108,108,111
            if (ch == '\r') {
                continue;
            }

            if (ch == '\n') {
                return sb.toString(); //hello
            } else {
                sb.append((char)ch); //hello
            }
        }

        // 為了防止資料丢失,判斷sb的長度不能大于0
        if (sb.length() > ) {
            return sb.toString();
        }

        return null;
    }

    /*
     * 先寫一個關閉方法
     */
    public void close() throws IOException {
        this.r.close();
    }
}
           
  • 自定義類模拟LineNumberReader的特有功能
    • 擷取每次讀取資料的行号
public class MyLineNumberReaderTest {
    public static void main(String[] args) throws IOException {
        // MyLineNumberReader mlnr = new MyLineNumberReader(new FileReader(
        // "my.txt"));

        MyLineNumberReader2 mlnr = new MyLineNumberReader2(new FileReader(
                "my.txt"));

        // mlnr.setLineNumber(10);

        // System.out.println(mlnr.getLineNumber());
        // System.out.println(mlnr.getLineNumber());
        // System.out.println(mlnr.getLineNumber());

        String line = null;
        while ((line = mlnr.readLine()) != null) {
            System.out.println(mlnr.getLineNumber() + ":" + line);
        }

        mlnr.close();
    }
}





public class MyLineNumberReader2 extends MyBufferedReader {
    private Reader r;

    private int lineNumber = ;

    public MyLineNumberReader2(Reader r) {
        super(r);
    }

    public int getLineNumber() {
        return lineNumber;
    }

    public void setLineNumber(int lineNumber) {
        this.lineNumber = lineNumber;
    }

    @Override
    public String readLine() throws IOException {
        lineNumber++;
        return super.readLine();
    }
}