java.lang.StringIndexOutOfBoundsException:引起长度= 7;指数= 7的Android的Java [英] Caused by: java.lang.StringIndexOutOfBoundsException: length=7; index=7 Android java
问题描述
您好我使用的功能为十六进制字符串字节数组,它给了我这个错误,有时它的工作原理有些时候提示错误
产生的原因:java.lang.StringIndexOutOfBoundsException:长度= 7;指数= 7>在java.lang.String.indexAndLength(String.java:500)
在java.lang.String.charAt(String.java:494)
块引用>公共静态的byte [] hexStringToByteArray(String s)将{
INT LEN = s.length();
字节[]数据=新字节[len个/ 2]; 的for(int i = 0; I< LEN;我+ = 2){
数据[I / 2] =(字节)((Character.digit将(s.charAt(ⅰ),16)所述; 4;)+ Character.digit将(s.charAt第(i + 1),16));
} 返回的数据;
}错误出现在这code和
为什么它工作的大部分时间,只有时它使应用程序强制关闭,任何人可以解决这一问题,以便它可以总是工作我用上面这个功能,使CRC32 checsum到的ByteArray
这是我用得到CRC32 checsum
功能私人字符串chesum(){ 字符串文件名=file.bin; 尝试{ CheckedInputStream顺= NULL; 尝试{
//计算CRC32校验
顺=新CheckedInputStream(
新的FileInputStream(文件名),新CRC32()); }赶上(FileNotFoundException异常五){
通信System.err.println(找不到文件); } 字节[] buf中=新的字节[128];
而(cis.read(BUF)GT; = 0){
} 长校验= cis.getChecksum()的getValue()。 字符串SS = Long.toHexString(校验); cis.close();
返回SS; }赶上(IOException异常五){
e.printStackTrace(); }
返回null;
}在这之后我称之为hexstringtobytearray功能
解决方案的for(int i = 0; I< LEN-1; I + = 2){
数据[I / 2] =(字节)((Character.digit将(s.charAt(ⅰ),16)所述; 4;)+ Character.digit将(s.charAt第(i + 1),16));
}更改条件
LEN
到LEN -1
Hi i use function to hex string to byte array and it gives me this error sometimes it works some times it gives error
Caused by: java.lang.StringIndexOutOfBoundsException: length=7;index=7 > at java.lang.String.indexAndLength(String.java:500) at java.lang.String.charAt(String.java:494)
public static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len/2]; for(int i = 0; i < len; i+=2){ data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16)); } return data; }
error comes in this code and why it works most of the time and only sometimes it makes application force close,can anybody fix this so that it can work always
i use this function above to make crc32 checsum to bytearray
here is the function i use to get crc32 checsum
private String chesum() { String fileName = "file.bin"; try { CheckedInputStream cis = null; try { // Compute CRC32 checksum cis = new CheckedInputStream( new FileInputStream(fileName), new CRC32()); } catch (FileNotFoundException e) { System.err.println("File not found."); } byte[] buf = new byte[128]; while(cis.read(buf) >= 0) { } long checksum = cis.getChecksum().getValue(); String ss = Long.toHexString(checksum); cis.close(); return ss; } catch (IOException e) { e.printStackTrace(); } return null; }
after this method i call hexstringtobytearray function
解决方案for(int i = 0; i < len-1 ; i+=2){ data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16)); }
Change the condition
len
tolen -1
这篇关于java.lang.StringIndexOutOfBoundsException:引起长度= 7;指数= 7的Android的Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!