如何在Java中将一个或多个字符串转换为字节数组中的不同范围?

3
我有一组字段字符串,如姓名、用户ID、电子邮件等,需要放入特定大小的字节数组(1024字节)中。
我希望找到一个可以让我简单使用索引变量bufferPosition的方法/函数,就像以下代码一样:
byteArray[bufferPosition] += name += userID += email; bufferPosition += name.length() += userID.length() += email.length();
到目前为止,我发现的都是将字符串直接转换为字节数组的方法,以及一些看起来很繁琐的解决方法(例如将字符串的每个元素视为字符,转换为字节,创建循环结构并插入每个元素)。
编辑:后续
我还有一些字段是String[]数组,最多包含14个元素。这将是最繁琐的部分。我能否使用类似的for-each循环?我假设有一种极其聪明的方法可以解决这个问题。

单调乏味的方式才是正确的方式。 - Jonny Henly
你需要保存字段的偏移量(即位置)吗?还是只需要一个平坦的数组? - xerx593
我不确定我完全理解这个问题。我只需要将字符串依次输入到数组中。我假设这是一个平面数组。 - AlwaysQuestioning
2个回答

3

尝试使用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
}

你需要确保不超出数组的范围,但这只是一个简单的例子。


哇,太棒了!我会尝试第二个。谢谢! - AlwaysQuestioning
我还有一些需要转录到这个缓冲区的字段,它们本身就是字符串数组,最多可以容纳14个元素。我最终需要为它们重写那种代码吗?我希望有一种方法可以创建一个多维数组String[][] myField,然后进行类似的for:each循环。虽然我猜想这只是一厢情愿! - AlwaysQuestioning
你需要将每个元素转换为字节,因为数组本身将是一个包含要单独转换的“String”对象的对象。你可以尝试使用序列化来实现你想要的效果,但你可能需要付出一些额外的努力才能得到你想要的结果。 - Ryan J
我不确定这是否是一个可行的解决方案。当你反序列化那个字节数组时,你如何确定第一个字符串在哪里结束,第二个字符串从哪里开始? - evgeniy44

1
一个稍微改进的版本(感谢 @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;
}

...具有空值/溢出处理和动态数据处理能力 :-)

编辑:...以及一些可移植性考虑。(d.getBytes()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接