簡體   English   中英

從RandomAccessFile一次讀取一個整數數組

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

我正在嘗試從RandomAccessFile讀取一個整數數組。 但是,RandomAccessFile僅支持讀取字節數組。 到目前為止,我的代碼:

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告訴我:“無法從int []轉換為byte []”。 在CI中可以輕松地將int *轉換為char *,但是我不知道這是如何在Java中完成的。 如何用Java做到這一點?

您可以使用ByteBuffer 讀取為byteArray ,然后進行轉換。

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

檢查類似的問題

您是否嘗試過像這樣的readInt方法:

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

如果將int [] (byte[])tempArray為byte [],則由於信息丟失,因此不允許這樣做,因此不允許(byte[])tempArray

該方法采用byte []參數而不是int [],因此不能直接給出int []。 如果不允許數組類型擴展,而沒有數組的話,您可以像傳遞字節一樣使用,而方法接受int。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM