gpt4 book ai didi

java - 如何在Java中从文件中读取特定数量的字节到字节数组中?

转载 作者:行者123 更新时间:2023-12-01 10:06:57 25 4
gpt4 key购买 nike

我想读取文件的 128 字节并将其放入字节数组中以对 128 字节进行一些处理。这应该迭代文件的整个长度(即每次读取接下来的 128 个字节并将其存储到字节数组中并进行处理)。我目前能够将文件中的所有字节读取到单个字节数组中。

public static void main(String[] args) throws IOException {

Path path = Paths.get("path/t/file");
byte[] bytes = Files.readAllBytes(path); }

任何帮助将不胜感激。

最佳答案

您应该只使用 FileInputStream:

    try {
File file = new File("file.ext");
RandomAccessFile data = new RandomAccessFile(file, "r");

byte[] fullBytes = new byte[(int) file.length()];
byte[] processBytes = new byte[128];

for (long i = 0, len = file.length() / 128; i < len; i++) {
data.readFully(processBytes);

// do something with the 128 bytes (processBytes).
processBytes = ByteProcessor.process(processBytes)

// add the processed bytes to the full bytes array
System.arraycopy(processBytes, 0, fullBytes, processBytes.length, fullBytes.length);

}

} catch (IOException ex) {
// catch exceptions.
}

关于java - 如何在Java中从文件中读取特定数量的字节到字节数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36375959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com