初始化数据类型大小"Long"字节数组?



所以我有这种方法将文件中的数据读取到一个字节数组中,起点为"偏移量",长度为"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变量不超过允许的最大值,就可以正常工作。 但是当我必须使用"long"作为变量len的数据类型才能传递更大的数字(即创建 lager 数组)时,我得到以下错误:

../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));
        }   
    }
}

你可能可以看看这个链接堆栈溢出

一句话,在对基元进行类型转换之前,请务必检查原语的范围。在这里,您希望字节数组大小采用长整型值,这在我看来是一个无效的情况,因为长可以在其范围内具有精度。地板/天花板的精度值肯定会导致精度损失。

最新更新