[英]Reading bytes in a file :java.lang.NegativeArraySizeException
I have gone through the similar posts but none of them really answered my question.我浏览过类似的帖子,但没有一个真正回答我的问题。 Hence I post my question in a separate thread.
因此,我在一个单独的线程中发布了我的问题。 I need to skip some bytes in the file which I am reading in the byte array.I am trying to achieve this through code below
我需要跳过我在字节数组中读取的文件中的一些字节。我试图通过下面的代码来实现这一点
1. byte [] readBytesToSKip = null;
2. readBytesToSKip = new byte[(int)bytesToSkip];
3. bytesReadToSkip = System.in.read(readBytesToSKip) ;
4. if(bytesReadToSkip > 0)
5. {
6. baos_.write(readBytesToSKip, 0, bytesReadToSkip);
7. }
But I get a NegativeArraySizeException
at line 2 where the size exceeds Integer.MAX_VALUE
.但我在第 2 行收到
NegativeArraySizeException
,其中大小超过Integer.MAX_VALUE
。 I am not sure how to achieve this otherwise.否则我不确定如何实现这一目标。
bytesToSkip
is long as I calculate in function below: bytesToSkip
很长,我在下面的函数中计算:
public static long bytesToLong1(byte[] bytes) {
long value = 0;
for (int i = 0; i < bytes.length; i++)
{
value = (value << 8) + (bytes[i] & 0xff);
}
return value;
}
Starting from your posted bytes->long
function从您发布的
bytes->long
函数开始
public static long bytesToLong1(byte[] bytes) {
long value = 0;
for (int i = 0; i < bytes.length; i++)
{
value = (value << 8) + (bytes[i] & 0xff);
}
return value;
}
Whenever bytes.length==8
and the first byte is >= 128
in absolute value (in Java specific: it's a negative byte value), you'll end having a negative value for your long.每当
bytes.length==8
并且第一个字节的绝对值 >= 128
(在 Java 中特定:它是一个负字节值)时,您的 long 将结束为负值。
Example:例子:
byte vals[]={0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
System.out.println(bytesToLong1(vals));
will result it -1
being printed.将导致它
-1
被打印。 Which will convert quite fine to an int
with a -1
value, but will still be improper for the length of an array.这将很好地转换为具有
-1
值的int
,但对于数组的长度仍然不合适。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.