简体   繁体   English

从RandomAccessFile一次读取一个整数数组

[英]Read an array of ints at once from RandomAccessFile

I am trying to read an array of ints from a RandomAccessFile. 我正在尝试从RandomAccessFile读取一个整数数组。 RandomAccessFile however only supports reading for an array of bytes. 但是,RandomAccessFile仅支持读取字节数组。 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[]". Eclipse告诉我:“无法从int []转换为byte []”。 In CI could easily cast int* to char* but I do not know how this is done in Java. 在CI中可以轻松地将int *转换为char *,但是我不知道这是如何在Java中完成的。 How could I do this in Java? 如何用Java做到这一点?

You can use ByteBuffer . 您可以使用ByteBuffer Read as a byteArray and then convert. 读取为byteArray ,然后进行转换。

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

Check similar question . 检查类似的问题

have you tried readInt method like: 您是否尝试过像这样的readInt方法:

    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. 如果将int [] (byte[])tempArray为byte [],则由于信息丢失,因此不允许这样做,因此不允许(byte[])tempArray

The method takes byte[] parameter not int[] so cannot give int[] directly. 该方法采用byte []参数而不是int [],因此不能直接给出int []。 In case of array type widening is not allowed, while without array you can do like pass byte while method accepts int. 如果不允许数组类型扩展,而没有数组的话,您可以像传递字节一样使用,而方法接受int。

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

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