2012-12-29 40 views
0

我想將字節轉換爲字符串。在將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

但我不想使用這個解決方案,因爲我在我的應用程序的很多地方使用了這個東西。那麼,有沒有其他的方式來實現這件事?

請建議我一個很好的解決方案,它適用於所有情況。我認爲最後的第二個解決方案會很好。 (檢查在字節數組中包含0,然後應用子字符串函數)。

+0

那豈不是更容易和更快地也使用SQLite作爲數據庫? – jlordo

回答

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); 
} 
+0

非常感謝,這看起來不錯,靈魂:) –

0

我覺得這條線會導致錯誤

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

s.indexOf(0) 

返回-1,也許你應該specifiy的ASCII碼 零是48

所以這將工作s = s.substring(0, s.indexOf(48));

檢查文檔對的indexOf(INT)

public int indexOf(int c)既然:API Level 1在此字符串中搜索指定字符的第一個索引 。 字符的搜索從頭開始,並移向此 字符串的末尾。

參數c要查找的字符。返回指定字符的該字符串 中的索引,如果未找到該字符,則返回-1。

+0

這裏'indexOf(0)'和'indexOf(48)'是不同的東西。所以'indexOf(48)'不會工作 –

相關問題