简体   繁体   English

读取 InputStream 字节并写入 ByteArrayOutputStream

[英]Reading InputStream bytes and writing to ByteArrayOutputStream

I have code block to read mentioned number of bytes from an InputStream and return a byte[] using ByteArrayOutputStream.我有代码块从 InputStream 读取提到的字节数并使用 ByteArrayOutputStream 返回一个字节 []。 When I'm writing that byte[] array to a file, resultant file on the filesystem seems broken.当我将该 byte[] 数组写入文件时,文件系统上的结果文件似乎已损坏。 Can anyone help me find out problem in the below code block.谁能帮我找出下面代码块中的问题。

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

My understanding of the problem statement我对问题陈述的理解

Read bytes number of bytes from the given InputStream in a ByteArrayOutputStream .ByteArrayOutputStream中的给定InputStream中读取字节数。
Finally, return a byte array .最后,返回一个字节数组

Key observations主要意见

  • A lot of work is done to make sure bytes are read in chunks of 8KB.做了大量工作以确保以 8KB 的块读取字节。
    Also, the last remaining chunk of odd size is read separately.此外,最后剩余的奇数块被单独读取。

  • A lot of work is also done to make sure we are reading from the correct offset.还做了很多工作来确保我们从正确的偏移量中读取。

My views我的看法

  • Unless we are reading a very large file (>10MB) I don't see a valid reason for reading in chunks of 8KB.除非我们正在读取一个非常大的文件(>10MB),否则我看不到读取 8KB 块的正当理由。

  • Let Java libraries do all the hard work of maintaining offset and making sure we don't read outside limits.让 Java 库完成所有艰苦的工作来维护偏移量并确保我们不会读取外部限制。 Eg: We don't have to give offset, simply do inputStream.read(b) over and over, the next byte array of size b.length will be read.例如:我们不必给出偏移量,只需一遍又一遍地执行inputStream.read(b) ,将读取下一个大小为 b.length 的字节数组。 Similarly, we can simply write to outputStream .同样,我们可以简单地写入outputStream

Code代码

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

References参考

About InputStreams关于输入流
Byte Array to Human Readable Format 字节数组到人类可读格式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM