添加多个字节数组

时间:2015-01-19 11:55:21

标签: java bytearray

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

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

1 个答案:

答案 0 :(得分:1)

为什么不创建一个用于封装每一行的类?

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

然后创建一个将在rs.next()循环中填充的ArrayList matchList。

然后你只需要:

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
}

如果你想发送所有匹配togheter,你必须做一个循环来计算列表中的总字节数,因为列表中的每个匹配将具有不同的字节大小(描述更改,标题字符等)