简体   繁体   English

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

[英]How to read a specific number of bytes from a file into a bytes array in Java?

I would like to read 128 bytes of my file and put into a byte array to do some processing with the 128 bytes. 我想读取文件的128个字节,并放入一个字节数组中,以对128个字节进行一些处理。 This should iterate over the entire length of the file (ie everytime read the next 128 bytes and store into a bytes array and do the processing). 这应该遍历文件的整个长度(即每次读取下一个128个字节并存储到一个字节数组中并进行处理)。 I am currently able to read all the bytes from the file into a single byte array. 我目前能够将文件中的所有字节读取到一个字节数组中。

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

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

Any help would be deeply appreciated. 任何帮助将不胜感激。

You should just use FileInputStream: 您应该只使用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.
    }

Here is something you can do. 您可以执行以下操作。

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

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

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