Question

I am trying to read an array of ints from a RandomAccessFile. RandomAccessFile however only supports reading for an array of bytes. My code so far:

public long getSumOfElementsFromArray(long start, int length)
{
    int[] tempArray = new int[length];
    try
    {
        RAF.seek(start);
        RAF.readFully( (byte[]) (tempArray) , 0, length*4);
        //do some stuff with tempArray
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    return 0;
}

Eclipse tells me: "Cannot cast from int[] to byte[]". In C I could easily cast int* to char* but I do not know how this is done in Java. How could I do this in Java?

Était-ce utile?

La solution

You can use ByteBuffer. Read as a byteArray and then convert.

int[] tempArray = ByteBuffer.wrap(byteArray).asIntBuffer().array();

Check similar question.

Autres conseils

have you tried readInt method like:

    for (int i = 0; i < tempArray.length; i++) {
            tempArray[i] = RAF.readInt();
    }

if you cast int[] to byte[], it is not allowed as there is a loss of info, so (byte[])tempArray not allowed.

The method takes byte[] parameter not int[] so cannot give int[] directly. In case of array type widening is not allowed, while without array you can do like pass byte while method accepts int.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top