0

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

我有一个 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 == 10then 使其不做 subString 条件,否则check contains 0 in byte array

但我不想使用这个解决方案,因为我在我的应用程序的很多地方都使用了这个东西。那么,有没有其他方法可以实现这件事呢?

请建议我一些适用于各种条件的好的解决方案。我认为最后第二个解决方案会很棒。(检查字节数组中是否包含 0,然后应用子字符串函数)。

4

2 回答 2

1
public String getStringFromBytes(byte[] inputBytes) {
    String s;
    s = new String(inputBytes);
    int zeroIndex = s.indexOf(0);
    return zeroIndex < 0 ? s : s.substring(0, zeroIndex);
}
于 2012-12-29T09:35:16.037 回答
0

我认为这条线会导致错误

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

s.indexOf(0)

返回 -1 ,也许您应该将 ASCII 代码指定为零,即48

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

检查 indexOf(int) 的文档

public int indexOf (int c) 自:API 级别 1 在此字符串中搜索指定字符的第一个索引。对字符的搜索从开头开始并移向该字符串的末尾。

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

于 2012-12-29T09:34:00.277 回答