添加多个字节数组

Add multiple bytes array

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

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

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

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
}

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