在将bytearray转换为固定长度的字符串时,请获得例外



我想将字节转换为字符串。

我有一个Android应用程序,我正在使用flatfile进行数据存储。

假设我的flatfile中有很多记录。

在平面文件数据库中,我的记录大小是固定的,其10字符,在这里我存储了许多字符串记录序列。

但是,当我从平面文件中读取一个记录时,它是每个记录的固定字节数。因为我为每个记录写了10个字节。

如果我的字符串是S="abc123";然后将其存储在abc123 ASCII values for each character and rest would be 0的平面文件中。均值字节阵列应为[97 ,98 ,99 ,49 ,50 ,51,0,0,0,0]。因此,当我想从字节数组中获取实际的字符串时,当时我使用以下代码,并且工作正常。

但是当我给我的inputString = "1234567890"时,它会产生问题。

public class MainActivity extends Activity {
    public static short messageNumb = 0;
    public static short appID = 16;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // record with size 10 and its in bytes.
        byte[] recordBytes = new byte[10];
        // fill record by 0's
        Arrays.fill(recordBytes, (byte) 0);
        // input string
        String inputString = "abc123";
        int length = 0;
        int SECTOR_LENGTH = 10;
        // convert in bytes
        byte[] inputBytes = inputString.getBytes();
        // set how many bytes we have to write.
        length = SECTOR_LENGTH < inputBytes.length ? SECTOR_LENGTH
                : inputBytes.length;
        // copy bytes in record size.
        System.arraycopy(inputBytes, 0, recordBytes, 0, length);
        // Here i write this record in the file.
        // Now time to read record from the file.
        // Suppose i read one record from the file successfully.
        // convert this read bytes to string which we wrote.
        Log.d("TAG", "String is  = " + getStringFromBytes(recordBytes));
    }
    public String getStringFromBytes(byte[] inputBytes) {
        String s;
        s = new String(inputBytes);
        return s = s.substring(0, s.indexOf(0));
    }
}

但是,当我的字符串具有10个字符时,我会遇到问题。当时我的字节数组中有两个0,所以在这一行中 s = s.substring(0, s.indexOf(0));

我得到以下例外:

java.lang.StringIndexOutOfBoundsException: length=10; regionStart=0; regionLength=-1
at java.lang.String.startEndAndLength(String.java:593)
at java.lang.String.substring(String.java:1474)

所以当我的字符串长度为10时,我该怎么办。

我有两个解决方案 - 我可以检查我的inputBytes.length == 10,然后使其不做substring条件,否则check contains 0 in byte array

,但我不想使用此解决方案,因为我在应用程序中的许多地方都使用了此东西。那么,还有其他方法可以实现这一目标吗?

请给我一些好的解决方案,这些解决方案在各种情况下都可以。我认为最后第二个解决方案将很棒。(Check在字节数组中包含0,然后应用子字符串函数)。

public String getStringFromBytes(byte[] inputBytes) {
    String s;
    s = new String(inputBytes);
    int zeroIndex = s.indexOf(0);
    return zeroIndex < 0 ? s : s.substring(0, zeroIndex);
}

我认为这线导致错误

s = s.substring(0, s.indexOf(0));
s.indexOf(0)

返回-1,也许您应该指定ASCII代码对于零是48

所以这将起作用s = s.substring(0, s.indexOf(48));

检查索引(int)的文档

public int indexof(int c)以来:API级别1在此字符串中搜索 对于指定字符的第一个索引。搜索 角色始于开始,并朝这个结束时移动 字符串。

参数c要查找的字符。返回此字符串中的索引 指定字符的中,-1如果找不到字符。

最新更新