Java SequenceInputStream 序列流

Java SequenceInputStream 序列流


概述

  • 序列流可以把多個字節輸入流整合成一個, 從序列流中讀取數據時, 將從被整合的第一個流開始讀, 讀完一個之後繼續讀第二個, 以此類推

SequenceInputStream

  • 構造方法
構造方法 說明
SequenceInputStream(InputStream s1, InputStream s2) 整合兩個流
SequenceInputStream(Enumeration e) 整合多個流,多個流通過枚舉方式傳入
  • 方法
方法 說明
read() 從此輸入流中讀取下一個數據字節
read(byte[] b, int off, int len) 將最多 len 個數據字節從此輸入流讀入 byte 數組
close() 關閉此輸入流並釋放與此流關聯的所有系統資源

示例

  • 整合兩個流
InputStream input1 = null;
InputStream input2 = null;

SequenceInputStream input = null;
OutputStream output = null;

try{
    // 創建兩個輸入流
    input1 = new FileInputStream("E:/郭靜 - 心牆.mp3");
    input2 = new FileInputStream("E:/許廷鏗 - 遺物.mp3");

    // 創建序列流和輸出流
    input = new SequenceInputStream(input1,input2);
    output = new FileOutputStream("E:/歌曲整合.mp3");

    byte[] buffer = new byte[1024 * 8];
    int len;

    // 讀寫數據
    while((len = input.read(buffer)) > 0) {
        output.write(buffer, 0, len);
    }

    System.out.println("Done.");
}catch(IOException e) {
    e.printStackTrace();
}finally {
    try {
        // 關閉序列流
        if(input != null) {
            input.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try{
            // 關閉輸入流
            if(output != null) {
                output.close();
            }
        }catch(IOException e) {
            e.printStackTrace();
        }
    }
}
  • 整合多個流
InputStream input1 = null;
InputStream input2 = null;
InputStream input3 = null;

SequenceInputStream input = null;
OutputStream output = null;

try{
    // 創建兩個輸入流
    input1 = new FileInputStream("E:/郭靜 - 心牆.mp3");
    input2 = new FileInputStream("E:/許廷鏗 - 遺物.mp3");
    input3 = new FileInputStream("E:/方雅賢 - 遇到.mp3");

    Vector<InputStream> vec = new Vector<>();
    vec.add(input1);
    vec.add(input2);
    vec.add(input3);

    // 將 Vector 中的元素取出,存入枚舉中
    Enumeration<InputStream> elements = vec.elements();

    // 創建序列流和輸出流
    input = new SequenceInputStream(elements);
    output = new FileOutputStream("E:/歌曲整合.mp3");

    byte[] buffer = new byte[1024 * 8];
    int len;

    // 讀寫數據
    while((len = input.read(buffer)) > 0) {
        output.write(buffer, 0, len);
    }

    System.out.println("Done.");
}catch(IOException e) {
    e.printStackTrace();
}finally {
    try {
        // 關閉序列流
        if(input != null) {
            input.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try{
            // 關閉輸入流
            if(output != null) {
                output.close();
            }
        }catch(IOException e) {
            e.printStackTrace();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章