簡體   English   中英

初始化大小為“ Long”數據類型的字節數組?

[英]initializing Byte array with size of “Long” data type?

所以我有這種方法可以將文件中的數據讀入字節數組,起始點為“ offset”,長度為o“ len”:

public static byte[] readFileDataToByteArray( File inFile, long offset, int len ) {

    byte[] buffer = new byte[ len ];

    try {
        RandomAccessFile in = new RandomAccessFile( inFile, "r" );
        in.seek( off );
        in.read( buffer );          
        in.close();
    } catch ( IOException e ) {
        System.err.println("Error readSentence: Error reading " + inFile ); 
        System.exit(1);
    }
    return buffer;
}

現在,只要len變量不超過允許的最大int值,此方法就可以正常工作。 但是當我必須使用“ long”作為變量len數據類型以便能夠傳遞更大的數字(即創建更大的數組)時,出現以下錯誤:

../util/Common.java:564: error: possible loss of precision
    byte[] buffer = new byte[ len ];
                              ^
required: int
found:    long
1 error

因此,基本上我要做的就是創建一個字節數組,其大小為“長”數據類型。 有什么提示嗎?

我剛剛嘗試過。 最大數組大小不能超過堆大小。 因此,如果可能的話,最好多次處理文件。

public class RandomAccessFileTest {
    static public class LargeArray {
        public long offset;
        public long len;
        public int arraySize; // can't exceed JVM heap size
        byte[] byte_arr;

        public LargeArray(long offset, long len, int arraySize) {
            this.offset = offset;
            this.len    = len;
            this.arraySize = arraySize;
        }
    }

    public static LargeArray readFileDataToByteArray(File inFile, LargeArray  array) {
        long count = array.len/array.arraySize;
        if (array.len > 0 ) {
            try{
                int arr_len = (count == 0) ? (int)array.len:array.arraySize;
                array.byte_arr = new byte[arr_len];
                RandomAccessFile in = new RandomAccessFile( inFile, "r" );
                in.seek( array.offset );
                in.read( array.byte_arr );          
                in.close();

                array.offset += arr_len;
                array.len    -= arr_len;
                return array;
            } catch ( IOException e ) {
                System.err.println("Error readSentence: Error reading " + inFile ); 
                System.exit(1);
            }       
        }
        return null;
    }

    public static void main(String[] args) {

        LargeArray array = new LargeArray(5,1000000, 10000);
        File file = new File("test.txt");

        while((array = readFileDataToByteArray(file, array)) != null) {
            System.out.println(new String(array.byte_arr));
        }   
    }
}

您可能可以檢查出此鏈接stackOverflow

小心一點,在對原型進行分類之前,請務必先檢查它們的范圍。 在這里,您希望字節數組的大小為long值,這對我來說似乎是無效的情況,因為long可以在其范圍內保持精度。 精度值的下限/上限肯定會導致精度損失。

暫無
暫無

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

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