简体   繁体   中英

Read an array of ints at once from RandomAccessFile

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 CI could easily cast int* to char* but I do not know how this is done in Java. How could I do this in Java?

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

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

Check similar question .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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