【问题标题】:How to read a specific number of bytes from a file into a bytes array in Java?java - 如何从文件中读取特定数量的字节到Java中的字节数组中?
【发布时间】:2023-03-05 08:56:01
【问题描述】:

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

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

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

任何帮助将不胜感激。

【问题讨论】:

  • byte[] bytes = new byte[128]; then.. 做他上面说的很容易
  • ...并检查返回值 - 最后一次读取通常比数组长度短 - 然后为 EOF 为 -1。
  • @3kings 如何读取第二组 128 字节?
  • 我发布了一个答案只是为了更清楚

标签: java arrays file byte


【解决方案1】:

你应该只使用 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.
    }

【讨论】:

  • ... 应该遍历文件的整个长度。 也许可以改进一下?
  • 就像我从文件中读取前 128 个字节一样。然后读取接下来的 128 个字节......继续这样做直到我到达文件的末尾
【解决方案2】:

这是你可以做的。

public void byteStuff()
    {
        File file= new File("PATHT TO FILE");
        FileInputStream input= new FileInputStream(file);

        byte[] bytes = new byte[128];

        while((input.read(bytes)) != -1)
        {
            //byte array is now filled. Do something with it.
            doSomething(bytes);
        }
    }

【讨论】:

  • 请注意,这不一定一次读取 128 个字节 - 它读取 最多 128 个字节。
  • @AndyTurner 啊,好吧,有没有办法一次读取 128 个字节?也许像下面的答案?
  • 不,这个答案和它的问题一样。您需要检查读取的字节数(read 的返回值),然后继续读取直到获得 128 个字节。
  • @Andy Turner 如何查看读取函数的返回值?你能编辑上面的代码让它读 128 字节吗?谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多