2015-01-19 4 views
1

각 행에서 다중 바이트 배열을 추가한다는 것은 모든 변수를 변수에 추가해야한다는 의미입니다. 그러나 이것은 변경할 수 없으므로 빈 바이트 배열을 인쇄합니다. 더 많은 바이트를 추가하려면 어떻게해야합니까?다중 바이트 배열 추가

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

'combineBytes'는 무엇을합니까? – SubOptimal

+0

@SubOptimal "match"의 모든 배열에 대해 배열 복사를 사용하여 "matches"에 배열을 추가하고 오프셋을 증가시킵니다. (오프셋은 전역 변수이므로 0으로 재설정되지 않습니다.) – Kenny

+0

[ByteArrayOutputStream] (http://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayOutputStream.html)을 사용해야 할 수도 있습니다.). 이렇게하면 "동적 인"bytearray를 가질 수 있습니다. – Flown

답변

1

왜 각 행을 캡슐화하기위한 클래스를 만들지 않습니까?

그런 다음 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); 
} 

그것은 : 당신이 모든을 togheter 일치 보낼 경우, 당신은 목록의 각 매치가 있기 때문에 목록의 총 바이트 수를 계산하기 위해 루프를 할 필요가

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

바이트 단위의 다른 크기 (설명 변경, 타이틀 챈트 등)

+0

감사합니다. 좀 잃어 버렸습니다. 모든 것을 바이트로 변환 할 수 있습니까? – Kenny

+0

모든 것을 말하면 매치 오른쪽의 속성만을 의미합니까? 매치 드, matchtitle, matchdescription 등 좋아? – Solano

+0

그래, 그거야. 모든 속성은 고정 길이입니다. – Kenny