簡體   English   中英

讀取 InputStream 字節並寫入 ByteArrayOutputStream

[英]Reading InputStream bytes and writing to ByteArrayOutputStream

我有代碼塊從 InputStream 讀取提到的字節數並使用 ByteArrayOutputStream 返回一個字節 []。 當我將該 byte[] 數組寫入文件時,文件系統上的結果文件似乎已損壞。 誰能幫我找出下面代碼塊中的問題。

public byte[] readWrite(long bytes, InputStream in) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    int maxReadBufferSize = 8 * 1024; //8KB
    long numReads = bytes/maxReadBufferSize;
    long numRemainingRead = bytes % maxReadBufferSize;
    for(int i=0; i<numReads; i++) {
        byte bufr[] = new byte[maxReadBufferSize];
        int val = in.read(bufr, 0, bufr.length);
        if(val != -1) {
            bos.write(bufr);
        }
    }
    if(numRemainingRead > 0) {
        byte bufr[] = new byte[(int)numRemainingRead];
        int val = in.read(bufr, 0, bufr.length);
        if(val != -1) {
            bos.write(bufr);
        }
    }
    return bos.toByteArray();
}

我對問題陳述的理解

ByteArrayOutputStream中的給定InputStream中讀取字節數。
最后,返回一個字節數組

主要意見

  • 做了大量工作以確保以 8KB 的塊讀取字節。
    此外,最后剩余的奇數塊被單獨讀取。

  • 還做了很多工作來確保我們從正確的偏移量中讀取。

我的看法

  • 除非我們正在讀取一個非常大的文件(>10MB),否則我看不到讀取 8KB 塊的正當理由。

  • 讓 Java 庫完成所有艱苦的工作來維護偏移量並確保我們不會讀取外部限制。 例如:我們不必給出偏移量,只需一遍又一遍地執行inputStream.read(b) ,將讀取下一個大小為 b.length 的字節數組。 同樣,我們可以簡單地寫入outputStream

代碼

public byte[] readWrite(long bytes, InputStream in) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] buffer = new byte[(int)bytes];

    is.read(buffer);
    bos.write(buffer);

    return bos.toByteArray();
}

參考

關於輸入流
字節數組到人類可讀格式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM