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

时间:2016-04-02 16:41:56

标签: java arrays file byte

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

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

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

任何帮助都将深表感谢。

2 个答案:

答案 0 :(得分: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.
    }

答案 1 :(得分:0)

这是你可以做的事情。

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