Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

JAVA 基礎再回首(二十三):基本類型流、記憶體操作流、打印流、隨機訪問流、合併流與序列化流

編輯:關於 Android 程式設計

有些日子沒寫了,這陣子確實比較忙,抱歉。話不多說,我們把 IO 流剩下的幾個知識點一次收尾。

一、操作基本資料類型的流

這一組是 DataInputStream 與 DataOutputStream。顧名思義,它們能直接讀寫 byte、short、int、long、float、double、char、boolean 等基本型別,不必自己手動處理位元組的組合與拆分。

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

    private static void write() throws IOException {
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("dos.txt"));
        dos.writeByte(10);
        dos.writeShort(100);
        dos.writeInt(1000);
        dos.writeLong(10000);
        dos.writeFloat(12.34F);
        dos.writeDouble(12.56);
        dos.writeChar('a');
        dos.writeBoolean(true);
        dos.close();   // 釋放資源
    }

    private static void read() throws IOException {
        DataInputStream dis = new DataInputStream(new FileInputStream("dos.txt"));
        byte b   = dis.readByte();
        short s  = dis.readShort();
        int i    = dis.readInt();
        long l   = dis.readLong();
        float f  = dis.readFloat();
        double d = dis.readDouble();
        char c   = dis.readChar();
        boolean bb = dis.readBoolean();
        dis.close();

        System.out.println(b);
        System.out.println(s);
        System.out.println(i);
        System.out.println(l);
        System.out.println(f);
        System.out.println(d);
        System.out.println(c);
        System.out.println(bb);
    }
}

先執行寫入、再執行讀取,可以看到各型別都能正確還原。要注意讀寫順序必須與寫入順序完全一致,否則資料型別會錯位,讀出來的結果就是亂數。

二、記憶體操作流

這一族一共有三組:

  • 操作位元組陣列:ByteArrayInputStream、ByteArrayOutputStream
  • 操作字元陣列:CharArrayReader、CharArrayWriter
  • 操作字串:StringReader、StringWriter

它們主要用於處理臨時資料。臨時資料的特性是「用完即丟、不需要落地存檔」,用記憶體操作流比寫檔再讀檔快得多。

public class ByteArrayStreamDemo {
    public static void main(String[] args) throws IOException {
        // 寫入:位元組陣列輸出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        for (int x = 0; x < 10; x++) {
            baos.write(("hello" + x).getBytes());
        }

        // 查看原始碼可以發現 close() 其實什麼都沒做,所以不關也無妨
        // baos.close();

        byte[] bys = baos.toByteArray();

        // 讀取:位元組陣列輸入流
        ByteArrayInputStream bais = new ByteArrayInputStream(bys);
        int by = 0;
        while ((by = bais.read()) != -1) {
            System.out.print((char) by);
        }
        // bais.close();
    }
}

上面寫的是英文字元,用位元組陣列輸出流沒問題。如果要寫入中文,就該改用操作字元陣列的 CharArrayWriter,避免位元組被切碎造成亂碼。至於字元陣列與字串這兩組的用法大同小異,這裡就不重複示範,留給大家自己練手。

三、打印流

打印流分兩類:位元組打印流 PrintStream,以及字元打印流 PrintWriter。我們平常用的 System.out 就是一個 PrintStream 物件。

它的特性可以整理成四點:

  • 只有寫、沒有讀。
  • 只能操作目的地,不能操作資料來源。
  • 可以操作任意類型的資料。
  • 若啟動自動刷新(autoFlush),能在特定條件下自動刷新緩衝。

順帶複習一個問題:哪些流物件可以直接操作純文字檔?答案是 FileInputStream、FileOutputStream、FileReader、FileWriter、PrintStream、PrintWriter。判斷依據很簡單——查 API 的建構子,若同時提供 File 型別與 String 型別的參數版本,通常就代表它能直接指向檔案。

print() 與 println() 的差別,實測一次就很清楚:

// 版本一:不換行
public class PrintWriterDemo {
    public static void main(String[] args) throws IOException {
        PrintWriter pw = new PrintWriter("pw2.txt");
        pw.print(true);
        pw.print(100);
        pw.print("hello");
        pw.close();
    }
}

// 版本二:每次都換行,並開啟自動刷新
public class PrintWriterDemo {
    public static void main(String[] args) throws IOException {
        PrintWriter pw = new PrintWriter(new FileWriter("pw2.txt"), true);
        pw.println("hello");
        pw.println(true);
        pw.println(100);
        pw.close();
    }
}

執行後對比兩個檔案,差異一目了然。由此可以推出:println() 其實等價於 bw.write(); + bw.newLine(); + bw.flush(); 三個動作的組合。

用打印流複製檔案

先拆解需求:把 1.txt 複製到 Copy.txt(前提是你确实有 1.txt 且有內容)。

  • 資料來源:1.txt → 讀取 → FileReader → 包一層 BufferedReader 提升效率
  • 目的地:Copy.txt → 寫出 → FileWriter → BufferedWriter → PrintWriter
public class CopyFileDemo {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("DataStreamDemo.java"));

        PrintWriter pw = new PrintWriter(new FileWriter("Copy.java"), true);

        String line = null;
        while ((line = br.readLine()) != null) {
            pw.println(line);
        }

        pw.close();
        br.close();
    }
}

跟傳統寫法比起來乾淨多了吧:

// 傳統版本
BufferedReader br = new BufferedReader(new FileReader("1.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("Copy.txt"));

String line = null;
while ((line = br.readLine()) != null) {
    bw.write(line);
    bw.newLine();
    bw.flush();   // 少了這行,檔案內容可能不完整
}

差別就在這裡:以前得自己 write、自己換行、自己 flush;現在 println() 一次搞定。

四、隨機訪問流

RandomAccessFile

這個類有點特別:它並不繼承自流體系,而是直接繼承 Object,但同時融合了 InputStream 與 OutputStream 的能力,支援對檔案做「隨機位置」的讀取與寫入。

建構子 RandomAccessFile(String name, String mode) 的第一個參數是檔案路徑,第二個參數是操作模式。模式共四種,最常用的是 "rw"——既能讀也能寫。

public class RandomAccessFileDemo {
    public static void main(String[] args) throws IOException {
        RandomAccessFile raf = new RandomAccessFile("raf.txt", "rw");
        raf.writeInt(100);
        raf.writeChar('a');
        raf.writeUTF("中國");
        raf.close();
    }
}

執行完寫入後,接著示範讀取與指標操作:

public class RandomAccessFileDemo {
    public static void main(String[] args) throws IOException {
        RandomAccessFile raf = new RandomAccessFile("raf.txt", "rw");

        int i = raf.readInt();
        System.out.println(i);
        System.out.println("目前指標位置:" + raf.getFilePointer());

        char ch = raf.readChar();
        System.out.println(ch);
        System.out.println("目前指標位置:" + raf.getFilePointer());

        String s = raf.readUTF();
        System.out.println(s);
        System.out.println("目前指標位置:" + raf.getFilePointer());

        // 想重新讀那個 char,就把指標移回去
        raf.seek(4);
        ch = raf.readChar();
        System.out.println(ch);
    }
}

重點在 getFilePointer() 與 seek():前者取得當前檔案指標位置,後者任意移動指標。正是這個能力,讓 RandomAccessFile 成為實作斷點續傳的關鍵——檔案傳到哪、下次從哪續傳,都由指標位置決定。我之前做影片斷點上傳時用的就是它,之後會另外整理成一篇總結。

五、合併流

SequenceInputStream

顧名思義,它能將多個輸入流串接成一個,因此也被稱為合併流。建構子有兩個:

  • SequenceInputStream(InputStream s1, InputStream s2)
  • SequenceInputStream(Enumeration<? extends InputStream> e)

以往只能把一個檔案複製到另一個檔案,有了合併流就能把多個檔案的內容寫進同一個檔案。

// 需求:把兩個檔案的內容合併到 Copy.java
public class SequenceInputStreamDemo {
    public static void main(String[] args) throws IOException {
        InputStream s1 = new FileInputStream("ByteArrayStreamDemo.java");
        InputStream s2 = new FileInputStream("DataStreamDemo.java");

        SequenceInputStream sis = new SequenceInputStream(s1, s2);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("Copy.java"));

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

        bos.close();
        sis.close();
    }
}

執行後打開 Copy.java,會看到兩個檔案的內容依序排列。

那要合併三個以上呢?改用 Enumeration 版本即可。Vector.elements() 的返回值型別正是 Enumeration,剛好可以對接:

// 需求:把三個檔案的內容合併到 Copy.java
public class SequenceInputStreamDemo2 {
    public static void main(String[] args) throws IOException {
        Vector<InputStream> v = new Vector<InputStream>();
        v.add(new FileInputStream("ByteArrayStreamDemo.java"));
        v.add(new FileInputStream("CopyFileDemo.java"));
        v.add(new FileInputStream("DataStreamDemo.java"));

        Enumeration<InputStream> en = v.elements();
        SequenceInputStream sis = new SequenceInputStream(en);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("Copy.java"));

        // 讀寫邏輯跟以前完全一樣
        byte[] bys = new byte[1024];
        int len = 0;
        while ((len = sis.read(bys)) != -1) {
            bos.write(bys, 0, len);
        }

        bos.close();
        sis.close();
    }
}

想合併四個、五個,只要繼續把輸入流物件加進 Vector 就好,讀寫部分完全不用改。這也是使用集合的價值:數量變動時,程式碼結構不必跟著動。

六、序列化流

這一組包含序列化流 ObjectOutputStream 與反序列化流 ObjectInputStream。

  • 序列化流:把物件以「流」的形式存到檔案或送到網路上。物件 → 流資料。
  • 反序列化流:把檔案或網路中的流資料還原成物件。流資料 → 物件。

首先準備一個實體類別,並實作 Serializable 介面:

public class Person implements Serializable {
    private String name;
    private int age;

    public Person() { super(); }

    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    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; }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }
}

寫入物件:

public class ObjectStreamDemo {
    public static void main(String[] args) throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("oos.txt"));

        Person p = new Person("阿杜", 25);
        oos.writeObject(p);

        oos.close();
    }
}

讀出物件:

public class ObjectStreamDemo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("oos.txt"));

        Object obj = ois.readObject();

        ois.close();
        System.out.println(obj);
    }
}

輸出結果:Person [name=阿杜, age=25]

用更正式的語言描述這兩個概念:

  • 物件序列化:將物件狀態轉換為可保存或可傳輸的過程。格式通常是與平台無關的二你就能在磁碟上長期保存,也能透過網路送到另一個節點。
  • 物件反序列化:把這種二話不多說,我們把 IO 流剩下的幾個知識點一次收尾。

    一、操作基本資料類型的流

    這一組是 DataInputStream 與 DataOutputStream。顧名思義,它們能直接讀寫 byte、short、int、long、float、double、char、boolean 等基本型別,不必自己手動處理位元組的組合與拆分。

    public class DataStreamDemo {
        public static void main(String[] args) throws IOException {
            // write();
            read();
        }
    
        private static void write() throws IOException {
            DataOutputStream dos = new DataOutputStream(new FileOutputStream("dos.txt"));
            dos.writeByte(10);
            dos.writeShort(100);
            dos.writeInt(1000);
            dos.writeLong(10000);
            dos.writeFloat(12.34F);
            dos.writeDouble(12.56);
            dos.writeChar('a');
            dos.writeBoolean(true);
            dos.close();   // 釋放資源
        }
    
        private static void read() throws IOException {
            DataInputStream dis = new DataInputStream(new FileInputStream("dos.txt"));
            byte b   = dis.readByte();
            short s  = dis.readShort();
            int i    = dis.readInt();
            long l   = dis.readLong();
            float f  = dis.readFloat();
            double d = dis.readDouble();
            char c   = dis.readChar();
            boolean bb = dis.readBoolean();
            dis.close();
    
            System.out.println(b);
            System.out.println(s);
            System.out.println(i);
            System.out.println(l);
            System.out.println(f);
            System.out.println(d);
            System.out.println(c);
            System.out.println(bb);
        }
    }

    先執行寫入、再執行讀取,可以看到各型別都能正確還原。要注意讀寫順序必須與寫入順序完全一致,否則資料型別會錯位,讀出來的結果就是亂數。

    二、記憶體操作流

    這一組包含三種:ByteArrayInputStream 與 ByteArrayOutputStream 操作位元組陣列;CharArrayReader 與 CharArrayWriter 操作字元陣列;StringReader 與 StringWriter 操作字串。它們通常用來處理臨時資料——用完就可以丟掉、不需要落地的資訊。

    public class ByteArrayStreamDemo {
        public static void main(String[] args) throws IOException {
            // 寫入:位元組陣列輸出流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            for (int x = 0; x < 10; x++) {
                baos.write(("hello" + x).getBytes());
            }
    
            // 查看原始碼可以發現 close() 其實什麼都沒做,所以不關也無妨
            // baos.close();
    
            byte[] bys = baos.toByteArray();
    
            // 讀取:位元組陣列輸入流
            ByteArrayInputStream bais = new ByteArrayInputStream(bys);
            int by = 0;
            while ((by = bais.read()) != -1) {
                System.out.print((char) by);
            }
            // bais.close();
        }
    }

    上面寫入的是英文字元,用位元組陣列輸出流完全沒問題。但如果要寫入中文,就該改用 CharArrayWriter,因為中文字元在 UTF-8 下會佔多個位元組,用位元組陣列切開可能導致亂碼。字元陣列與字串的讀寫寫法大同小異,這裡就不重複示範,留給大家自己練手。

    三、打印流

    打印流分為位元組打印流 PrintStream 和字元打印流 PrintWriter。我們平常用的 System.out 就是一個 PrintStream 物件。

    打印流的特點可以歸納為四點:只有寫、沒有讀;只能操作目的地、不能操作資料來源;可以操作任意類型的資料;若啟動自動刷新(autoFlush),則在特定條件下會自動刷新緩衝。

    順帶複習一個問題:哪些流物件可以直接操作純文字檔?答案是 FileInputStream、FileOutputStream、FileReader、FileWriter、PrintStream、PrintWriter。判斷依據很簡單——查 API 的建構子,若同時提供 File 型別與 String 型別的參數版本,通常就代表它能直接指向檔案。

    print() 與 println() 的差別,實測一次就很清楚:

    // 版本一:不換行
    public class PrintWriterDemo {
        public static void main(String[] args) throws IOException {
            PrintWriter pw = new PrintWriter("pw2.txt");
            pw.print(true);
            pw.print(100);
            pw.print("hello");
            pw.close();
        }
    }
    
    // 版本二:每次都換行,並開啟自動刷新
    public class PrintWriterDemo {
        public static void main(String[] args) throws IOException {
            PrintWriter pw = new PrintWriter(new FileWriter("pw2.txt"), true);
            pw.println("hello");
            pw.println(true);
            pw.println(100);
            pw.close();
        }
    }

    分別執行這兩個範例,對比輸出的檔案內容,差異一目了然。由此我們還可以總結出一個結論:println() 方法其實等價於 bw.write(); 加上 bw.newLine(); 再加上 bw.flush(); 這三個動作的組合。

    用打印流複製檔案

    需求是把 1.txt 複製到 Copy.txt 中(前提是你确实有 1.txt,並且有內容)。先來拆解一下:

    • 資料來源:1.txt → 讀取 → FileReader → 高效緩衝 → BufferedReader
    • 目的地:Copy.txt → 寫出 → FileWriter → BufferedWriter → PrintWriter
    public class CopyFileDemo {
        public static void main(String[] args) throws IOException {
            // 封裝資料來源
            BufferedReader br = new BufferedReader(new FileReader("DataStreamDemo.java"));
    
            // 封裝目的地
            PrintWriter pw = new PrintWriter(new FileWriter("Copy.java"), true);
    
            String line = null;
            while ((line = br.readLine()) != null) {
                pw.println(line);
            }
    
            pw.close();
            br.close();
        }
    }

    這段程式碼比以前乾淨多了吧。如果你已經忘了以前是怎麼寫的,對比一下:

    // 傳統版本
    BufferedReader br = new BufferedReader(new FileReader("1.txt"));
    BufferedWriter bw = new BufferedWriter(new FileWriter("Copy.txt"));
    
    String line = null;
    while ((line = br.readLine()) != null) {
        bw.write(line);
        bw.newLine();
        bw.flush();   // 少了這行,檔案內容可能不完整
    }

    差別就在這裡:以前得自己呼叫 write、自己換行、自己 flush;現在 println() 一次搞定三件事。

    四、隨機訪問流

    RandomAccessFile

    這個類有點特別:它並不繼承自流體系,而是直接繼承 Object,但同時融合了 InputStream 與 OutputStream 的功能,支援對檔案進行隨機位置的讀取與寫入。

    建構子 RandomAccessFile(String name, String mode) 的第一個參數是檔案路徑,第二個參數是操作模式。模式共四種,最常用的是 "rw"——既能讀也能寫。

    public class RandomAccessFileDemo {
        public static void main(String[] args) throws IOException {
            RandomAccessFile raf = new RandomAccessFile("raf.txt", "rw");
            raf.writeInt(100);
            raf.writeChar('a');
            raf.writeUTF("中國");
            raf.close();
        }
    }

    執行完寫入後,接著示範讀取與指標操作:

    public class RandomAccessFileDemo {
        public static void main(String[] args) throws IOException {
            RandomAccessFile raf = new RandomAccessFile("raf.txt", "rw");
    
            int i = raf.readInt();
            System.out.println(i);
            System.out.println("目前指標位置:" + raf.getFilePointer());
    
            char ch = raf.readChar();
            System.out.println(ch);
            System.out.println("目前指標位置:" + raf.getFilePointer());
    
            String s = raf.readUTF();
            System.out.println(s);
            System.out.println("目前指標位置:" + raf.getFilePointer());
    
            // 想重新讀那個 char,就把指標移回去
            raf.seek(4);
            ch = raf.readChar();
            System.out.println(ch);
        }
    }

    重點在 getFilePointer() 與 seek():前者取得當前檔案指標位置,後者任意移動指標。正是這個能力,讓 RandomAccessFile 成為實作斷點續傳的關鍵——檔案傳到哪、下次從哪續傳,都由指標位置決定。我之前做影片斷點上傳時用的就是它,之後會另外整理成一篇總結。

    五、合併流

    SequenceInputStream

    顧名思義,它能將多個輸入流串接成一個,因此也被稱為合併流。建構子有兩個:

    • SequenceInputStream(InputStream s1, InputStream s2)
    • SequenceInputStream(Enumeration<? extends InputStream> e)

    以往只能把一個檔案複製到另一個檔案,有了合併流就能把多個檔案的內容寫進同一個檔案。

    // 需求:把兩個檔案的內容合併到 Copy.java
    public class SequenceInputStreamDemo {
        public static void main(String[] args) throws IOException {
            InputStream s1 = new FileInputStream("ByteArrayStreamDemo.java");
            InputStream s2 = new FileInputStream("DataStreamDemo.java");
    
            SequenceInputStream sis = new SequenceInputStream(s1, s2);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("Copy.java"));
    
            byte[] bys = new byte[1024];
            int len = 0;
            while ((len = sis.read(bys)) != -1) {
                bos.write(bys, 0, len);
            }
    
            bos.close();
            sis.close();
        }
    }

    執行後打開 Copy.java,會看到兩個檔案的內容依序排列。

    那要合併三個以上呢?改用 Enumeration 版本即可。Vector.elements() 的返回值型別正是 Enumeration,剛好可以對接:

    // 需求:把三個檔案的內容合併到 Copy.java
    public class SequenceInputStreamDemo2 {
        public static void main(String[] args) throws IOException {
            Vector<InputStream> v = new Vector<InputStream>();
            v.add(new FileInputStream("ByteArrayStreamDemo.java"));
            v.add(new FileInputStream("CopyFileDemo.java"));
            v.add(new FileInputStream("DataStreamDemo.java"));
    
            Enumeration<InputStream> en = v.elements();
            SequenceInputStream sis = new SequenceInputStream(en);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("Copy.java"));
    
            // 讀寫邏輯跟以前完全一樣
            byte[] bys = new byte[1024];
            int len = 0;
            while ((len = sis.read(bys)) != -1) {
                bos.write(bys, 0, len);
            }
    
            bos.close();
            sis.close();
        }
    }

    想合併四個、五個,只要繼續把輸入流物件加進 Vector 就好,讀寫部分完全不用改。這也是使用集合的價值:數量變動時,程式碼結構不必跟著動。

    六、序列化流

    這一組包含序列化流 ObjectOutputStream 與反序列化流 ObjectInputStream。

    • 序列化流:把物件以「流」的形式存到檔案或送到網路上。物件 → 流資料。
    • 反序列化流:把檔案或網路中的流資料還原成物件。流資料 → 物件。

    首先準備一個實體類別,並實作 Serializable 介面:

    public class Person implements Serializable {
        private String name;
        private int age;
    
        public Person() { super(); }
    
        public Person(String name, int age) {
            super();
            this.name = name;
            this.age = age;
        }
    
        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; }
    
        @Override
        public String toString() {
            return "Person [name=" + name + ", age=" + age + "]";
        }
    }

    寫入物件:

    public class ObjectStreamDemo {
        public static void main(String[] args) throws IOException {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("oos.txt"));
    
            Person p = new Person("阿杜", 25);
            oos.writeObject(p);
    
            oos.close();
        }
    }

    讀出物件:

    public class ObjectStreamDemo {
        public static void main(String[] args) throws IOException, ClassNotFoundException {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("oos.txt"));
    
            Object obj = ois.readObject();
    
            ois.close();
            System.out.println(obj);
        }
    }

    輸出結果:Person [name=阿杜, age=25]

    用更正式的語言描述這兩個概念:

    • 物件序列化:將物件狀態轉換為可保存或可傳輸的過程。格式通常是與平台無關的二進位流,可以長期保存在磁碟上,也可以透過網路傳到另一個節點。
    • 物件反序列化:把這種二進位流資料重新還原成物件。

    一個實作上的小提醒:若類別新增或刪除了欄位,舊的序列化資料可能無法還原,實務上通常會宣告 serialVersionUID 來控制版本相容性。

    好了,IO 流就學到這裡。這一系列下來,從節點流、緩衝流、轉換流到現在 these 特殊功能的流,基本 Already 涵蓋了日常開發會用到的絕大多數場景。大家沒事的時候多練幾遍,把「讀寫四大步驟」和「裝飾模式的包裝順序」練到不用想就能寫出來,之後碰到任何新的流類別都能快速上手。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved