Java通过块将大文件读入字节数组块

时间:2016-09-08 20:10:44

标签: java

所以我一直在尝试制作一个将文件输入字节数组的小程序,然后将该字节数组转换为十六进制,然后转换为二进制。然后它将播放二进制值(我没有想到当我到达这个阶段时该怎么做),然后将其保存为自定义文件。

我研究了很多互联网代码,我可以将文件转换为字节数组并转换为十六进制,但问题是我无法将大文件转换为字节数组(内存不足)。

这是完全失败的代码

public void rundis(Path pp) {
    byte bb[] = null;

    try {
        bb = Files.readAllBytes(pp); //Files.toByteArray(pathhold);
        System.out.println("byte array made");
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (bb.length != 0 || bb != null) {
        System.out.println("byte array filled");
        //send to method to turn into hex
    } else {
        System.out.println("byte array NOT filled");
    }

}

我知道这个过程应该怎么做,但我不知道如何正确编码。

如果您有兴趣,请参阅:

  • 使用File
  • 输入文件
  • 通过文件块将块读取到字节数组中。防爆。每个字节数组记录保持600字节
  • 将该块发送为十六进制值 - > Integer.tohexstring
  • 将该十六进制值块发送为二进制值 - > Integer.toBinarystring
  • 乱用二进制值
  • 逐行保存到自定义文件

问题 ::我不知道如何通过要处理的块将一个巨大的文件转换为字节数组块。 任何和所有的帮助将不胜感激,感谢您阅读:)

2 个答案:

答案 0 :(得分:9)

要使用FileInputStream

分块输入
getEnvelope()

答案 1 :(得分:4)

要流式传输文件,您需要远离Files.readAllBytes()。它对于小文件来说是一个很好的实用工具,但是你注意到的不是大文件。

在伪代码中,它看起来像这样:

while there are more bytes available
    read some bytes
    process those bytes
    (write the result back to a file, if needed)

在Java中,您可以使用FileInputStream来阅读文件byte by bytechunk by chunk。让我们说我们想要回写我们处理过的字节。首先我们打开文件:

FileInputStream is = new FileInputStream(new File("input.txt"));
FileOutputStream os = new FileOutputStream(new File("output.txt"));

我们需要FileOutputStream来回复我们的结果 - 我们不想丢弃我们珍贵的处理数据,对吧?接下来我们需要一个包含大块字节的缓冲区:

byte[] buf = new byte[4096];

多少字节取决于你,我有点像4096字节的块。然后我们需要实际读取一些字节

int read = is.read(buf);

这将读取buf.length个字节并将其存储在buf中。它将返回读取的总字节数。然后我们处理字节:

//Assuming the processing function looks like this:
//byte[] process(byte[] data, int bytes);
byte[] ret = process(buf, read);
上面示例中的

process()是您的处理方法。它接受一个字节数组,它应该处理的字节数,并将结果作为字节数组返回。

最后,我们将结果写回文件:

os.write(ret);

我们必须在循环中执行它,直到文件中没有剩余字节为止,所以让我们为它写一个循环:

int read = 0;
while((read = is.read(buf)) > 0) {
    byte[] ret = process(buf, read);
    os.write(ret);
}

最后关闭流

is.close();
os.close();

就是这样。我们以4096字节的块处理文件,并将结果写回文件。由您决定如何处理结果,您也可以通过TCP发送它,甚至在不需要时删除它,甚至从TCP而不是读取文件,基本逻辑是一样的。

这仍然需要一些正确的错误处理来解决丢失的文件或错误的权限,但这取决于您实现它。

流程方法的示例实现:

//returns the hex-representation of the bytes
public static byte[] process(byte[] bytes, int length) {
    final char[] hexchars = "0123456789ABCDEF".toCharArray();
    char[] ret = new char[length * 2];
    for ( int i = 0; i < length; ++i) {
        int b = bytes[i] & 0xFF;
        ret[i * 2] = hexchars[b >>> 4];
        ret[i * 2 + 1] = hexchars[b & 0x0F];
    }
    return ret;
}
相关问题