I need to read the file into an array of 4 bytes. Those. 1 array element is 4 bytes of a file. How to do it? Or how to overwrite from a single-byte array to such one, shortening it by the number of elements 4 times?

    1 answer 1

    If you do not go into the details of the problem, the following code can solve the task:

    int[] result = new int[1000]; try ( DataInputStream stream = new DataInputStream(new BufferedInputStream(new FileInputStream("test.dat"))); ) { for(int i = 0; i < result.length; i++) { result[i] = stream.readInt(); } } catch(EOFException e) { System.out.println("Completed"); } 

    It uses the DataInputStream class, which allows you to read data from the underlying stream (file) in batches of one, two, four or eight bytes. The simplest data type with a length of four bytes is Integer, which is used in the code.

    It is worth noting that the byte order is not taken into account (Little Endian or Big Endian). But the class DataInputStream, in fact, does not allow to take it into account.

    • I would just keep order in order - Korolkov Sergey
    • The order is naturally preserved. Here the main question is what is this order. If the file is Big Endian, then the code above will work fine and you can not bother. If the file is Little Endian - but you need another option to think about. - slava