簡體   English   中英

如何在Java中的字節數組中將字符串或多個字符串轉換為不同的范圍?

[英]How can I convert a string or multiple strings into different ranges within a byte array in Java?

我有一組字符串,用於名稱,用戶ID,電子郵件等字段,需要進入一個特定大小(1024字節)的byte []數組。

我很想找到一個允許我簡單地使用我的索引變量bufferPosition的方法/函數,如下所示:

byteArray [bufferPosition] + = name + = userID + = email;

bufferPosition + = name.length()+ = userID.length()+ = email.length();

到目前為止,我所發現的只是直接將字符串轉換為字節數組的方法,以及解決此問題的一些看似乏味的方法(即將字符串的每個元素視為字符,轉換為字節,創建循環結構並插入每個元件)。

編輯:跟進

我還有String []數組的字段,最多包含14個元素。 這將是最乏味的部分。 我是否可以使用類似的for-each循環? 我假設有一種非常聰明的方法可以解決這個問題。

試試這個,使用System.arraycopy

// some dummy data
byte[] myByteArr = new byte[1024];
String name = "name";
String userId = "userId";
int bufferPosition = 0;

// repeat this for all of your fields...
byte[] stringBytes = name.getBytes();  // get bytes from string
System.arraycopy(stringBytes, 0, myByteArr, bufferPosition, stringBytes.length);  // copy src to dest
bufferPosition += stringBytes.length;  // advance index

您可以使用循環,以這種方式(使用您的字段名稱):

String[] myFields = new String[]{name, userID, email};  // put your fields in an array or list

// loop through each field and copy the data
for (String field : myFields) {
    byte[] stringBytes = field.getBytes();  // get bytes from string
    System.arraycopy(stringBytes, 0, myByteArr, bufferPosition, stringBytes.length);  // copy src to dest
    bufferPosition += stringBytes.length;  // advance index
}

您需要確保不超出數組的范圍,但這是一個簡單的示例。

稍微改進的版本(thx @Ryan J):

private static byte[] bytesFromStrings(final String... data) throws UnsupportedEncodingException {
    final byte[] result = new byte[1024];
    int bufferPosition = 0;
    if (data != null) {
        for (String d : data) {
            final byte[] stringBytes = d.getBytes("UTF-8");
            if (bufferPosition > 1023) {
                break;
            } else {
                System.arraycopy(stringBytes, 0, result, bufferPosition, Integer.min(1024 - bufferPosition, stringBytes.length));
                bufferPosition = Integer.min(bufferPosition + stringBytes.length, 1024);
            }   
        }
    }
    return result;
}

..with null /溢出處理和動態數據:-)

編輯:...和一些可移植性考慮因素。 d.getBytes()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM