Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何解决StringIndexOutOfBounds异常?_Java_Core - Fatal编程技术网

Java 如何解决StringIndexOutOfBounds异常?

Java 如何解决StringIndexOutOfBounds异常?,java,core,Java,Core,我正在复制我的程序,将二进制数据转换为十六进制格式,并以16字节的格式逐行打印数据,即使在打印了一定程度的数据后,我仍会收到StringIndexOutOfBounds异常。请帮助我解决此问题 byte[] buffer = new byte[16]; while((line = bis.read(buffer)) != -1) { for(int i = 0; i < line; i++) { value = Integer.toHexString(

我正在复制我的程序,将二进制数据转换为十六进制格式,并以16字节的格式逐行打印数据,即使在打印了一定程度的数据后,我仍会收到StringIndexOutOfBounds异常。请帮助我解决此问题

byte[] buffer = new byte[16];
while((line = bis.read(buffer)) != -1)
{
    for(int i = 0; i < line; i++)
    {   
        value = Integer.toHexString(0xFF & buffer[i] | 0x100).substring(1);
        sb.append(value);//I think here is the problem 
    }
    if(a == 0)
    {
        incValue = sb.substring(0, 32);
        System.out.println(incValue);
    }
    else 
    {
        counter = counter + 32;
        incValue = sb.substring(counter, counter + 32);
        System.out.println(incValue);
    }
    a++;
与此相反:

 incValue = sb.substring(counter, counter + 32);
您可以使用以下选项:

if((counter+32)< sb.length())
{
  incValue = sb.substring(counter, counter + 32);
}
else
{
  incValue = sb.substring(counter) //The String is shorter than counter+32 chars
}
if((计数器+32)
第一个循环每读取一个字节会追加2个字符,但是
sb.substring()
调用始终假定追加了32个字符。如果读取少于16个字符会发生什么情况?您应该尝试使用像Eclipse这样的IDE来调试正在发生的事情,因为调试应用程序不是这个网站的目标。
的文档说:
抛出:IndexOutOfBoundsException-如果开始或结束为负数,如果结束大于长度(),或者如果开始大于结束
,您可以将此帖子设置为答案吗?Thx:)^^
if((counter+32)< sb.length())
{
  incValue = sb.substring(counter, counter + 32);
}
else
{
  incValue = sb.substring(counter) //The String is shorter than counter+32 chars
}