gpt4 book ai didi

java - 添加多个字节数组

转载 作者:太空宇宙 更新时间:2023-11-04 06:16:34 25 4
gpt4 key购买 nike

我从每一行添加多个字节数组,这意味着我需要将它们全部附加到一个变量中。但这会打印一个空字节数组,因为它无法更改。我可以做什么来附加更多字节?

ResultSet rs = stmt.executeQuery(query);
int matchesLength = 0;

try {
boolean b = rs.last();

if (b) {
matchesLength = rs.getRow();
}
}
catch (SQLException e) {
e.printStackTrace();
}

byte[] matches = new byte[118 * matchesLength];

while ( rs.next() ) {
String matchId = rs.getString("id");
String matchTitle = rs.getString("title");
String matchDescription = rs.getString("description");
int matchPlayers = rs.getInt("max_players");
int matchMaxPlayers = rs.getInt("max_players");
String matchHostId = rs.getString("host_id");

short matchPlayersShort = (short) matchPlayers;
byte[] matchPlayersBytes = ByteBuffer.allocate(2).putShort(matchPlayersShort).array();

short matchMaxPlayersShort = (short) matchMaxPlayers;
byte[] matchMaxPlayersBytes = ByteBuffer.allocate(2).putShort(matchMaxPlayersShort).array();

byte[][] match = {
String.format("%1$-" + 32 + "s", matchId).getBytes(),
String.format("%1$-" + 22 + "s", matchTitle).getBytes(),
String.format("%1$-" + 44 + "s", matchDescription).getBytes(),
matchPlayersBytes,
matchMaxPlayersBytes,
String.format("%1$-" + 16 + "s", matchHostId).getBytes()
};

// global offset variable, for each array copy
combineBytes(match, matches);
}

最佳答案

为什么不创建一个类来封装每一行?

public class Match{
private String matchId;
private String matchTitle;
private String matchDescription;
etc....

set and get for all variables;

public byte[] getBytes(){
here a logic to transform this attributes in a array of bytes
}
}

然后创建一个 ArrayList matchList,该列表将填充到 rs.next() 循环中。

那么你只需要:

while(rs.next()){
match = new Match();
match.setBlabla(rs.get(value));
....all sets
list.add(match);
}

当您通过套接字将其发送到客户端时,您只需读取列表并使用字节执行逻辑。

假设您有一个包含 10 行的列表,并且希望将其表示为字节。

ArrayList<Match> matchList = new ArrayList<Match>();
Match m;
while(rs.next()){
m = new Match();
m.set // one set for each attribute getting the value from rs.get
matchList.add(m);
}

现在发送:

for(Match m : matchList){
byte[] bytesToSend = m.getBytes(); //you defined this method
send(bytesTosend) //one match send for time
}

如果您想一起发送所有匹配项,则必须执行循环来计算列表中的总字节数,因为列表中的每个匹配项将具有不同的字节大小(描述更改、标题颂歌等)

关于java - 添加多个字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28024092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com