Index out of bounds exception: getting same row repeated several times - java

This is my code which I use to take in an Excel sheet, read its contents and to each row I add a GUID from a list I have.
UPDATE
Code:
public class PublishOutputFile {
public void publishOutputWithGuids(List<String> guids, File file)
throws Exception {
FileInputStream fileStream = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(fileStream);
HSSFSheet sheet = workbook.getSheetAt(0);
Row toprow = sheet.getRow(0);
int cellsNum = toprow.getLastCellNum();
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
int rownum = row.getRowNum();
System.out.println(rownum);
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
break;
case Cell.CELL_TYPE_NUMERIC:
break;
case Cell.CELL_TYPE_STRING:
break;
}
if (rownum == 0) {
row.createCell(cellsNum).setCellValue("GUID");
} else {
// System.out.println(rownum);
row.createCell(cellsNum).setCellValue(guids.get(rownum-1));
}
}
}
fileStream.close();
FileOutputStream out = new FileOutputStream(
new File(
"C:/Users/U0172959/Desktop/Themes_20131120_234645-hierarchy with GUIDS.xls"));
workbook.write(out);
out.close();
}
}
UPDATE Output:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 286, Size: 286
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at mappingForEtl.PublishOutputFile.publishOutputWithGuids(PublishOutputFile.java:43)
at mappingForEtl.InputFileParsing.main(InputFileParsing.java:75)
In the output, every row is being repeated like 5 times and I think this is what causes the out of bounds exception. But I can't figure out what's causing this to happen.
(I have used the same code for a different file yesterday, and that worked fine... ) Can it have anything to do with the number of columns in the excel sheet I take as input. The one I used yesterday had 8 columns, the one I am using now has 20.
Anyone has any idea what might be causing this? Thanks for help.

You are iterating over the cells within a row and for each cell you print the row number. Are you very sure that the data you print the right values in your else case?
if (row.getRowNum() == 0) {
row.createCell(cellsNum).setCellValue("GUID");
} else {
System.out.println((row.getRowNum())); // row number for each cell?
row.createCell(cellsNum).setCellValue(guids.get((row.getRowNum())));
}
Update:
The problem with the repeated output is that you have a loop over your rows. Each row consists of a number of cells. You loop over the cells as well. The repeated output comes from the fact, that while you loop through the cells in the row, the row does not change.
For better understanding, you should change your output to that:
System.out.println("Being at row: " + row.getRowNum() + " creating cell at cellnum: " + cellsNum);
That should clean up the understanding of what is going on.
Update 2:
The IndexOutOfBoundsException is thrown because the size of guid is 286 but the index is zero based and does not start by 1. As you tread the first row different, you should change guids.get(row.getRowNum()) to guids.get(row.getRowNum() - 1). That can work but it does not have to. As long as we don't know the detailed data structure, it might be of no value for you...

About the Exception
You may have accidentaly created some new Row (probably blank) and there is no GUID on your List for that Row. That could cause this Exception.
Maybe this addition helps you:
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
if (row.getLastCellNum() < cellsNum)
continue;
About the repeated output
You are iterating over each row, and then iterating over each cell, and then printing the row number. Considering a row has 4 cells, this would end up printing the Row number 4 times.

The problem is here:
} else {
row.createCell(cellsNum).setCellValue(
guids.get((row.getRowNum())));
}
Your guids.get is throwing the exception since it doesn't contain an element at index 286.
Solution: retrieve the element at index in row.getRowNum - 1, so you will now retrieve elements from 0 to 285:
} else {
row.createCell(cellsNum).setCellValue(
guids.get((row.getRowNum() - 1)));
}
Update:
Since it looks you're not trying to solve the IndexOutOfBoundsException (very odd) but more about why the numbers are printed 4 to 5 times, then review your current algorithm:
Iterator<Row> rowIterator = sheet.iterator();
//verify if there's a row to read in the current Excel sheet
while (rowIterator.hasNext()) {
//get the row
Row row = rowIterator.next();
//get an iterator of the cells
Iterator<Cell> cellIterator = row.cellIterator();
//while there's a cell to read...
while (cellIterator.hasNext()) {
//get the cell
//note: if the cell is empty, it won't be considered by the CellIterator, so even
//if you open the file and see 20 cells, this Iterator will seek for cells with some value
//from your current output, this looks to be only 5 cells
Cell cell = cellIterator.next();
//verify the type of the cell...
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
//do nothing?
break;
case Cell.CELL_TYPE_NUMERIC:
//do nothing?
break;
case Cell.CELL_TYPE_STRING:
//do nothing?
break;
}
if (row.getRowNum() == 0) {
row.createCell(cellsNum).setCellValue("GUID");
} else {
//prints the number of the row (per cell)
//this causes the 1\n1\n1\n1\n2\n2\n... output
System.out.println((row.getRowNum()));
//writes the element in guids at index of row num
row.createCell(cellsNum).setCellValue(
//guids.get((row.getRowNum())));
guids.get((row.getRowNum() - 1)));
}
}
}

Related

What is the parseBase64Binary function in Python?

In Java, I use:
String str = “%EF!c&WrDwCCTe<fX$,#8L<YTs?G5d>F])ub.63G=Xn<cdef2R{47JQexxN”;
byte[] result = DatatypeConverter.parseBase64Binary(str);
for(byte i : result){
System.out.print(i);
System.out.print(" ");
}
to decode str.
Output:
16 87 22 -84 60 2 9 55 -97 95 -62 -40 78 -63 -71 116 91 -101 -21 113 94 119 29 121 -3 -111 -29 -78 80 123 28 77
Now I need to decode str with Base64 in python but I don't know which lib and function should I choose.
I've tried base64.b64decode but its result is different from that in Java.
str = '%EF!c&WrDwCCTe<fX$,#8L<YTs?G5d>F])ub.63G=Xn<cdef2R{47JQexxN'
result = base64.b64decode(str)
print(result)
for i in range(0, len(decode_secret)):
print(decode_secret[i], end=" ")
Output:
b'\x10W\x16\xac<\x02\t7\x9f_\xc2\xd8N\xc1\xb9t[\x9b\xebq'
16 87 22 172 60 2 9 55 159 95 194 216 78 193 185 116 91 155 235 113

Blowfish decrypting hex encoded string

I'm trying to decrypt Hex encoded string via Blowfish. But the result is different from the correct one.
String s="a1d0534e4baf9e670bde8670caee8b87"
String decKey = "R=U!LH$O2B#";
Cipher m_decrypt = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
m_decrypt.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decKey.getBytes(),"Blowfish"));
byte[] decrypted = m_decrypt.doFinal(Hex.decodeHex(s.toCharArray()));
Correct result from site: c6 b7 8d 52 31 35 30 34 31 38 38 36 39 37 02 02
My result: -58 -73 -115 82 49 53 48 52 49 56 56 54 57 55
I check the correct byte array with mine on this site http://blowfish.online-domain-tools.com/
The correect result: c6 b7 8d 52 31 35 30 34 31 38 38 36 39 37 02 02
is in hex encoding and contains two bytes of padding.
My result: -58 -73 -115 82 49 53 48 52 49 56 56 54 57 55
in in signed decimal encoding without the padding bytes.
They are the same value just in different encodings where "My result" has had the padding removed as is usual.

HashMap deleting itself inside a HashMap

The goal of my project is to create a League of teams, and have rosters of each teams. I'm supposed to use 2 different maps. One map is for holding the Team name as a string, with it's object (Team). The other map is for holding the roster with the number and the object (Player). Whenever I run this code, and try to test whether the roster is printing out the right numbers, I have a problem. The roster seems to clear itself whole. I know that I have put a Roster.clear() method in, but that is to reset the roster to put players from other teams in. If you need the team class, I will put it in at the bottom. Thank you SO much if anyone is able to answer my question.
import java.util.*;
public class League{
public League(Scanner s){
Map<String,Team> League = new HashMap<String,Team>();
Map<Integer,Player> Roster = new HashMap<Integer, Player>();
Team t;
Player p;
String team,
name;
Boolean throwsRightHanded;
int number,
position,
plateApp,
walks,
strikeouts,
hits,
inningsPitched,
earnedRuns,
atBats,
runsBattedIn,
homeRuns,
hitByPitch;
team = s.next();
while (s.hasNext()){
if (!s.hasNext("-1")){
number = s.nextInt();
name = s.next();
position = s.nextInt();
if (s.next() == "t"){
throwsRightHanded = true;
}
else{
throwsRightHanded = false;
}
plateApp = s.nextInt();
walks = s.nextInt();
strikeouts = s.nextInt();
hits = s.nextInt();
if (position == 1){
//Pitcher
inningsPitched = s.nextInt();
earnedRuns = s.nextInt();
p = new Pitcher(inningsPitched, earnedRuns, number, name, position,
throwsRightHanded, plateApp, walks, strikeouts, hits);
}
else{
atBats = s.nextInt();
runsBattedIn = s.nextInt();
homeRuns = s.nextInt();
hitByPitch = s.nextInt();
p = new PositionPlayer(atBats, runsBattedIn, homeRuns, hitByPitch, number, name, position,
throwsRightHanded, plateApp, walks, strikeouts, hits);
}
Roster.put(number, p);
}
else{
t = new Team(team, Roster);
League.put(team, t);
Roster.clear();
s.next();
if (s.hasNext())
team = s.next();
}
}
Iterator<Team> it = League.values().iterator();
Team teamIterator;
while (it.hasNext()){
teamIterator = it.next();
System.out.println(teamIterator);
Iterator<Player> itt = teamIterator.getRoster().values().iterator();
while (itt.hasNext()){
System.out.println(itt.next());
}
}
}
The important part is below:
else{
t = new Team(team, Roster);
League.put(team, t);
Roster.clear();
s.next();
if (s.hasNext())
team = s.next();
}
}
Iterator<Team> it = League.values().iterator();
Team teamIterator;
while (it.hasNext()){
teamIterator = it.next();
System.out.println(teamIterator);
Iterator<Player> itt = teamIterator.getRoster().values().iterator();
while (itt.hasNext()){
System.out.println(itt.next());
}
}
}
Team Class:
public class Team{
private Map<Integer,Player> roster;
private String t;
public Team(String tname, Map<Integer,Player> floatroster){
setRoster(floatroster);
t = tname;
}
public String lookupPlayer(int n){
if (!roster.containsKey(n)){
System.out.println("No player with number " + n + " is on the roster for the " + t);
return null;
}
else{
return roster.values().toString();
}
}
public String toString(){
return t;
}
public void setRoster(Map<Integer,Player> floatroster){
roster = floatroster;
}
public Map<Integer, Player> getRoster(){
return roster;
}
}
File I'm reading from:
RedSox
65 Jonathan 1 t 416 23 80 111
259 32
68 Matt 1 t 399 28 56 90
241 37
32 Craig 1 f 383 29 55 121
245 35
11 Clay 1 t 418 32 63 105
241 37
46 Ryan 1 t 408 24 59 97
228 35
51 Edwin 1 f 392 32 64 82
232 36
37 Heath 1 t 419 31 53 109
233 38
62 Rich 1 f 411 33 36 77
263 36
61 Brian 1 f 397 25 59 107
240 32
56 Joe 1 t 390 32 57 89
201 36
59 Tommy 1 f 408 26 69 104
284 35
64 Jean 1 t 421 44 37 94
263 33
70 Roman 1 t 428 31 46 91
252 35
20 Wade 1 f 386 36 49 73
256 38
41 Alex 1 t 418 28 61 70
240 36
60 Henry 1 f 401 26 74 115
255 37
22 Rick 1 t 420 20 65 88
226 36
66 Noe 1 t 408 27 61 80
225 36
52 Eduardo 1 f 365 34 67 100
217 34
28 Robbie 1 f 382 32 55 96
221 34
36 Junichi 1 t 401 23 60 88
267 39
19 Koji 1 t 364 28 47 113
236 35
67 Brandon 1 t 392 25 66 122
210 37
10 Ryan 2 t 592 44 82 210
406 95 29 5
23 Blake 2 t 577 29 99 121
432 80 16 3
7 Christian 2 t 599 34 117 196
416 95 31 6
47 Travis 3 t 669 58 78 201
451 136 34 1
48 Pablo 5 t 628 45 74 139
368 96 1 0
13 Hanley 3 t 575 37 94 148
388 80 23 0
15 Dustin 4 t 635 36 105 227
304 113 28 1
26 Brock 4 t 1443 33 83 422
454 274 50 2
5 Allen 3 t 654 40 108 125
383 60 2 1
2 Xander 6 t 602 48 95 137
420 64 14 3
50 Mookie 8 t 584 35 84 199
323 110 31 7
25 Jackie 7 t 608 53 92 161
528 69 1 5
38 Rusney 9 t 626 47 69 194
422 135 31 0
34 David 3 f 567 63 99 108
399 55 1 6
-1
Yankees
38 Andrew 1 t 388 22 67 119
213 37
68 Dellin 1 t 364 34 65 86
265 32
26 Chris 1 f 397 19 74 118
232 35
65 Caleb 1 t 424 33 64 88
279 36
30 Nathan 1 t 381 35 59 85
250 37
74 Nick 1 t 417 33 80 92
235 33
33 Chris 1 t 414 25 52 85
238 38
48 Andrew 1 f 386 28 66 110
242 35
55 Brian 1 t 419 25 48 76
273 34
47 Ivan 1 t 445 24 51 108
256 35
67 James 1 f 427 26 51 120
217 37
57 Branden 1 t 416 22 73 106
212 37
35 Michael 1 t 398 28 61 109
283 35
50 Nick 1 t 426 24 62 95
231 37
45 Chasen 1 f 399 18 60 74
243 35
52 CC 1 f 397 23 49 108
234 35
40 Luis 1 t 405 20 64 131
240 38
19 Masahiro 1 t 420 31 26 89
195 33
43 Adam 1 t 416 28 54 98
240 33
41 Justin 1 f 365 26 49 104
251 35
34 Brian 2 t 637 41 79 147
365 66 1 1
66 John 2 t 584 58 81 150
434 92 21 1
53 Austin 2 t 593 47 98 122
423 62 17 3
73 Gary 2 t 709 43 66 194
407 152 35 2
31 Greg 3 t 672 66 78 157
299 60 1 5
14 Stephen 4 t 607 44 53 158
390 99 16 5
18 Didi 6 t 613 33 55 217
479 126 29 3
12 Chase 5 t 553 58 97 146
332 83 2 5
63 Jose 4 t 683 49 124 124
380 71 12 2
64 Robert 4 t 662 43 96 144
395 65 6 2
17 Brendan 4 t 658 55 61 162
382 96 28 2
29 Dustin 7 t 587 63 82 156
461 119 22 1
36 Carlos 9 t 545 50 94 129
373 90 4 4
22 Jacoby 8 f 657 42 43 142
473 51 1 3
11 Brett 7 f 551 32 120 145
406 131 26 1
72 Slade 8 f 543 50 97 132
399 70 23 2
70 Rico 9 t 646 22 83 259
433 175 40 6
25 Chris 9 t 576 34 103 153
432 74 6 3
-1
BlueJays
56 Mark 1 f 440 21 63 123
208 33
27 Brett 1 f 405 31 63 117
218 36
50 Steve 1 t 438 30 74 106
251 38
43 RA 1 t 384 32 72 88
254 38
25 Marco 1 t 438 27 67 104
243 34
35 Jeff 1 f 409 32 63 100
228 32
32 LaTroy 1 t 402 21 66 57
261 36
31 Liam 1 t 380 25 74 100
252 34
36 Drew 1 t 375 26 78 83
251 36
64 Chad 1 t 421 27 63 97
253 31
62 Aaron 1 f 403 33 64 96
277 35
57 Mark 1 t 376 24 59 113
234 34
54 Roberto 1 t 423 21 58 121
247 34
14 David 1 f 432 26 54 119
201 38
41 Aaron 1 t 410 18 60 107
259 36
8 AJ 2 t 610 44 115 151
400 54 12 2
55 Russell 2 t 646 49 79 145
300 79 9 2
30 Dioner 2 t 686 38 71 111
434 76 21 4
15 Chris 3 t 606 47 77 126
440 53 11 3
20 Josh 5 t 605 63 100 150
446 48 8 1
17 Ryan 4 t 610 21 89 135
420 89 23 2
9 Cliff 4 t 531 73 94 169
442 47 14 4
13 Justin 3 f 651 40 85 158
380 82 5 3
2 Troy 6 t 658 38 87 127
399 57 16 2
19 Jose 9 t 712 44 115 239
429 145 28 1
3 Ezequiel 7 f 589 57 104 136
351 75 18 2
11 Kevin 8 t 671 41 81 158
380 155 31 1
45 Dalton 8 t 638 36 104 246
343 115 30 2
7 Ben 7 t 621 37 98 149
382 86 5 4
-1
Orioles
35 Brad 1 t 392 35 69 116
233 32
53 Zach 1 f 451 31 45 78
239 34
16 Wei-yin 1 f 359 25 59 108
237 39
71 Oliver 1 t 426 21 62 106
241 37
61 Jason 1 t 385 22 56 103
242 33
39 Kevin 1 t 383 33 59 104
229 38
60 Mychal 1 t 397 26 65 118
261 36
50 Miguel 1 t 411 32 64 83
236 36
31 Ubaldo 1 t 371 35 69 81
227 35
52 Steve 1 t 393 32 64 97
257 39
17 Brian 1 f 425 28 62 113
227 36
66 T.J. 1 f 386 30 66 91
244 35
56 Darren 1 t 395 29 75 97
265 35
65 Chaz 1 t 382 18 46 75
232 34
57 Jorge 1 t 406 20 58 93
242 33
30 Chris 1 t 394 38 67 89
226 33
63 Tyler 1 t 420 27 69 88
278 35
59 Mike 1 t 358 30 64 124
287 37
45 Steve 2 t 667 55 130 141
452 57 1 3
36 Caleb 2 t 545 48 81 165
403 47 10 0
32 Matt 2 t 625 55 97 119
453 46 0 2
19 Chris 3 t 636 40 88 95
438 54 0 2
3 Ryan 4 t 722 35 85 166
436 87 28 2
2 J.J. 6 t 668 52 99 164
417 136 32 1
15 Paul 6 t 734 33 99 141
524 78 1 1
13 Manny 5 t 665 39 63 137
420 45 10 3
6 Jonathan 4 t 744 44 70 146
402 57 17 4
34 Christian 3 t 617 40 109 128
447 58 19 3
12 Dariel 9 t 555 56 99 170
422 111 32 2
10 Adam 8 t 621 40 95 166
436 119 25 3
48 Junior 7 t 689 49 123 142
425 107 11 3
9 David 7 f 605 44 89 146
409 36 10 0
18 Gerardo 9 f 686 34 80 206
435 116 36 3
28 Steve 7 t 624 70 72 159
457 108 20 5
14 Nolan 7 t 682 55 91 140
369 62 6 5
-1
Rays
35 Matt 1 t 395 23 57 83
208 34
22 Chris 1 t 371 21 60 84
234 37
59 Andrew 1 t 420 27 60 105
250 30
26 Brad 1 t 376 28 66 110
259 37
31 Xavier 1 f 423 31 59 92
224 37
37 Alex 1 t 409 21 56 111
272 37
54 Steven 1 t 412 31 79 90
244 38
47 Brandon 1 t 407 22 69 102
226 36
51 Nathan 1 f 409 20 62 88
265 36
57 Jake 1 f 373 27 78 101
223 36
55 Matt 1 t 375 32 61 104
247 35
23 Jake 1 t 392 25 56 82
219 37
30 Erasmo 1 t 434 34 26 102
270 35
34 C.J. 1 f 408 25 69 87
235 35
45 Enny 1 f 391 26 63 106
211 35
33 Drew 1 f 385 28 75 98
226 39
49 Kirby 1 t 359 22 59 129
237 39
40 J.P. 2 t 612 39 114 163
393 99 28 2
46 Luke 2 t 593 56 124 191
371 201 38 0
44 Rene 2 t 670 39 94 158
438 62 1 3
1 Tim 4 t 630 44 98 157
390 155 29 2
13 Asdrubal 6 t 680 46 100 127
455 43 7 4
11 Logan 4 t 547 46 107 142
391 100 0 3
2 Nick 4 t 1065 47 76 214
496 157 32 4
21 James 3 t 638 56 97 217
397 103 29 1
3 Evan 5 t 624 61 102 140
442 63 16 3
36 Richie 3 t 658 36 81 143
419 63 0 2
5 Brandon 1 t 410 30 66 80
254 39
39 Kevin 1 t 414 34 63 84
238 35
27 Mikie 1 t 388 24 65 89
238 33
7 Daniel 1 t 384 23 61 89
259 35
24 Grady 1 t 371 29 68 106
224 38
20 Steven 1 t 406 16 54 103
247 35
-1
Since your input always ends each roster's data with a "-1", your current code is calling Roster.clear() -- clearing the Roster object right after it had been filled with data. That is one reason why your team rosters are always empty.
Also, you are re-using the same Roster object for every team. Every team needs its own roster.
To fix both of these issues, replace the Roster.clear() call with:
Roster = new HashMap<Integer, Player>();
That will ensure you have a new roster map for each roster, and that you never empty out a roster.

Different data when printing and writing to file

There is a stream of data which is sent from server. I need to store this byte stream into a file. The problem is the data which I output to console and the one which I store in a file are different. Seems like there is a change in format of data when I stored in a file.
Here is the program:
try
{
System.out.println("My Address is "+serverSocket.getLocalSocketAddress());
Socket server = serverSocket.accept(); // return a new socket
System.out.println("Connected to client "+server.getRemoteSocketAddress());
inputStream = server.getInputStream();
in = new DataInputStream(inputStream);
out = new FileOutputStream("output.txt");
ArrayList<Byte> bytes = new ArrayList<Byte>();
int curi;
byte cur;
byte[] curBytes = null;
int length = 0;
System.out.println("Before while loop");
while((curi = in.read())!=-1 && count!=500)
{
System.out.println(count+" Reading some data");
//out.write(curi);
cur = (byte)curi;
bytes.add(cur);
curBytes = getPrimativeArray(bytes);
String curBytesString = new String(curBytes, "UTF-8");
count++;
}
int i=0;
for(byte b : bytes)
{
System.out.print(b+" ");
curBytes[i] = b;
i++;
}
out.write(curBytes);
server.close();
}
catch(IOException e)
{
e.printStackTrace();
}
What I print using System.out.print(b+" "); and the one I store in curBytes[] are the same thing. But when I compare the console and file output, they are different.
Console output: 0 0 113 -100 -126 -54 0 32 14 1 0 0 1 -58 60 54 0 3 63 -2 85 74 -81 -88 0 9 1 24 85 74 -81 -48 0 13 65 -113 85 74 -81 -88 0 12 125 -126 85 74 -81 -88 0 13 21 97 85 74 -81 -88 0 13 31 19 85 74 -81 -48 0 13 42 24 0 6 0 0 0 0 0 0 0 0 0 0 32 0 7 -100 0 -5 6 -128 0 -56 29 -127 23 112 -1 -1 0 0 64 0 1 -121 28 115 105 112 58 43 49 52 50 50 50 48 57 57 57 49 53 64 111 110 101 46 97 116 116 46 110 101 116 28 115 105 112 58 43 49 52 50 50 50 48 57 57 57 54 53 64 111 110 101 46 97 116 116 46 110 101 116 37 50 57 54 53 45 49 53 48 53 48 54 50 51 50 55 48 50 45 50 48 53 48 54 54 50 55 54 54 64 48 48 55 56 48 48 49 49 16 32 1 5 6 64 0 0 0 32 16 0 0 0 120 0 17 16 32 1 24 -112 16 1 46 2 0 0 0 0 0 0 0 6 1 -113 0 4 0 33 -64 -42 0 91 5 8 0 9 0 -56 0 0 0 15 3 85 74 -81 -88 0 12 -120 -28 8 0 9 0 -56 0 0 0 15 3 85 74 -81 -88 0 12 -44 -39 8 0 4 0 -56 0 0 1 11 3 85 74 -81 -88 0 9 1 24 8 0 5 0 0 0 0 0 0 3 85 74 -81 -88 0 13 31 19 8 0 1 0 -56 0 0 0 6 3 85 74 -81 -48 0 13 42 24 -64 34 4 24 9 89 83 73 80 47 50 46 48 47 84 67 80 32 91 50 48 48 49 58 53 48 54 58 52 48 48 48 58 48 58 50 48 49 48 58 48 58 55 56 58 49 49 93 58 49 51 55 48 59 98 114 97 110 99 104 61 122 57 104 71 52 98 75 50 57 48 45 48 48 55 56 48 48 49 49 45 48 48 48 102 45 52 52 49 57 55 49 52 48 51 3 85 74 -81 -88 0 12 -120 -28 127 83 73 80 47 50 46 48 47 84 67 80 32 91 50 48 48 49 58 53 48 54 58 52 48 48 48 58 48 58 50 48 49 48 58 48 58 55 56 58 49 49 93 58 49 51 55 48 59 114 101 99 101 105 118 101 100 61 50 48 48 49
File Output: ^#^#q<9c><82>Ê^# ^N^A^#^#^AÆ<6^#^C?þUJ¯¨^# ^A^XUJ¯Ð^#^MA<8f>UJ¯¨^#^L}<82>UJ¯¨^#^M^UaUJ¯¨^#^M^_^SUJ¯Ð^#^M*^X^#^F^#^#^#^#^#^#^#^#^#^# ^#^G<9c>^#û^F<80>^#È^]<81>^Wpÿÿ^#^##^#^A<87>^\sip:+14222099915#one.att.net^\sip:+14222099965#one.att.net%2965-150506232702-2050662766#00780011^P ^A^E^F#^#^#^# ^P^#^#^#x^#^Q^P ^A^X<90>^P^A.^B^#^#^#^#^#^#^#^F^A<8f>^#^D^#!ÀÖ^#[^E^H^# ^#È^#^#^#^O^CUJ¯¨^#^L<88>ä^H^# ^#È^#^#^#^O^CUJ¯¨^#^LÔÙ^H^#^D^#È^#^#^A^K^CUJ¯¨^# ^A^X^H^#^E^#^#^#^#^#^#^CUJ¯¨^#^M^_^S^H^#^A^#È^#^#^#^F^CUJ¯Ð^#^M*^XÀ"^D^X YSIP/2.0/TCP [2001:506:4000:0:2010:0:78:11]:1370;branch=z9hG4bK290-00780011-000f-441971403^CUJ¯¨^#^L<88>ä^?SIP/2.0/TCP [2001:506:4000:0:2010:0:78:11]:1370;received=2001
Please let me know at what step I'm making a mistake.
The other answers here tell you to use a PrintWriter or a FileWriter instead of the FileOutputStream but I'm fairly sure that this is not what you want.
Your problem is that you're writing raw bytes to a file and then reading it back as characters and comparing that to byte values represented as characters and then printed with System.out.
Let's take a look at what happens when you print a byte with the value 65 (or 01000001 in binary).
When you use System.out.print you will invoke PrintStream.print(int) with the integer value of 65 which will in turn print the characters 6 and 5 to the terminal.
When you use out.write you will invoke FileOutputStream.write(byte[]) which will write the bits 01000001 to the file.
Later, when you check the contents of the file your tool will try to interpret this byte as a character and it will most likely use the ASCII encoding to do so (even if you're using Unicode as your default encoding this is likely what will happen since Unicode is a superset of ASCII). This results in the character A being printed.
If you want to view the output file in a way similar to what you've printed with System.out.print you can use the following command on linux:
$ hexdump -e '/1 "%i "' <file>
Example:
$ cat /etc/issue
Ubuntu 12.04.5 LTS \n \l
$ hexdump -e '/1 "%i "' /etc/issue
85 98 117 110 116 117 32 49 50 46 48 52 46 53 32 76 84 83 32 92 110 32
92 108 10 *
My first answer was wrong, so I am editing this because I made the assumption that you could write out a string to the FileOutputStream, but I don't think that is the case. FileOutputStream is only used for byte streams, so you've got to stick to that format when writing out to the file.
If you hold the data in a buffer[array], and then write those bytes out to a file that you have created using the output stream, it should work. I found this document that might be helpful.
The main idea is that somewhere in your code, the byte array isn't getting written to the file correctly. Perhaps its just a matter of adding the close() method.
out.close();
server.close();
reading and writing files in java
Here is the section I found useful.
import java.io.*;
public class Test {
public static void main(String [] args) {
// The name of the file to create.
String fileName = "temp.txt";
try {
// Put some bytes in a buffer so we can
// write them. Usually this would be
// image data or something. Or it might
// be unicode text.
String bytes = "Hello theren";
byte[] buffer = bytes.getBytes();
FileOutputStream outputStream =
new FileOutputStream(fileName);
// write() writes as many bytes from the buffer
// as the length of the buffer. You can also
// use
// write(buffer, offset, length)
// if you want to write a specific number of
// bytes, or only part of the buffer.
outputStream.write(buffer);
// Always close files.
outputStream.close();
System.out.println("Wrote " + buffer.length +
" bytes");
}
catch(IOException ex) {
System.out.println(
"Error writing file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
The console (System.out) is a PrintWriter, while the file output is a FileOutputStream.
The basic difference between Stream and Writer: Streams are supposed to manipulate "raw data", like numbers taken directly from binary format, while writers are used to manipulate "human-readable data", transforming all the data you write.
For example, the 6 int is different from the 6 character. When you use a stream, you write directly the int, while with a writer, the data wrriten is transformed into the character.
Then, if you want your file output to be the same as your console output, do not use FileOutputStream, but instead, use FileWriter, and it's method write(String).
How to make this work:
1 - replace out = new FileOutputStream("output.txt"); by out = new FileWriter("output.txt");
2 - replace out.write(curBytes); by:
for (byte b : curBytes) {
out.write(b + " ");
}
I would suggest you use IOUtils.copy and use a BufferedReader
to wrap your InputStream.
The output stream should obviously be FileOutputStream
I hope this helps

java string with extended ascii codes to byte arrary (allocate one byte per code)

I have a java nio socket server that needs to communicate with a C socket client. The C socket client sends data to the server with ASCII codes above 127, using one byte per ASCII code. The server needs to send back the same.
I need to convert a string into a byte array with the same length (one byte per code).
The string is like 1200üö001001001, where it contains some ascii codes above 127.
In the research I did, I did not find a solution. I tried this
byte[] b = "1200üö001001001".getBytes("UTF-8");
byte[] b = "1200üö001001001".getBytes("US-ASCII");
byte[] b = "1200üö001001001".getBytes("ISO-8859-1");
byte[] b = "1200üö001001001".getBytes();
Some of these convert üö into ?? or multiple bytes per ASCII code, causing a different length between byte array and string.
I needing some help.
This is an example of data that comes from the C socket client. dots are ascii codes from Client.
<code>
0000 00 ff 31 32 30 30 fc f6 00 01 08 e1 e0 00 00 00 ..1200..........
0010 00 00 14 00 00 00 31 36 34 36 30 30 32 38 30 30 ......1646002800
0020 30 30 30 30 30 34 31 38 30 31 32 30 30 30 30 30 0000041801200000
0030 30 30 30 30 30 30 31 30 30 30 30 30 30 30 30 30 0000001000000000
0040 30 30 31 30 30 30 30 30 30 30 30 30 30 30 31 30 0010000000000010
0050 30 30 36 31 30 30 30 30 30 30 36 31 30 30 30 30 0061000000610000
0060 30 30 35 31 35 39 31 31 31 34 30 39 32 33 31 33 0051591114092313
0070 32 31 31 32 33 32 30 35 31 34 30 39 32 33 30 36 2112320514092306
0080 39 39 39 39 39 39 30 30 30 30 30 35 35 31 35 39 9999990000055159
0090 31 31 33 32 39 38 20 20 20 20 33 38 38 33 33 38 113298 388338
00a0 38 33 20 20 20 20 20 20 20 42 41 43 20 50 41 4e 83 XXX PAN
00b0 41 4d 41 20 54 45 53 54 3e 48 4f 57 41 52 44 20 AMA TEST>HOWARD
00c0 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 50 P
00d0 41 30 32 33 30 30 31 30 30 31 31 30 30 32 30 30 A023001001100200
00e0 33 37 30 30 30 32 35 30 30 31 31 38 34 30 38 34 3700025001184084
00f0 30 38 34 30 30 30 30 39 31 31 30 30 30 30 30 30 0840000911000000
0100 31
This is the code i use to convert from hex string to byte array
line 4 i convert from binary eg. 1101 to equvalent hex string eg `3F`
line 13 i take the bitmap in hex string eg. `"fcf6000108e1e0000000000014000000"`
that contains 32 chars and try to convert to 16 bytes, but this results in 20 bytes
because some chars takes more than one byte
1 // Set bitmaps
2 if ( String.copyValueOf(zeros).indexOf("1", 64) == -1 ) { zeros[0] = '0'; }
3 tmp = String.copyValueOf(zeros);
4 bits = binToHex(tmp);
5
6 // check bits to send
7 if ( zeros[0] == '0') {
8 bits = bits.substring(0, 16);
9 }
10
11 // join message
12 tmp = sb.toString();
13 trm = isoCode + hexToASCII(bits) + tmp.substring(39);
14 System.out.println("Trama respuesta " + (new Timestamp((new Date()).getTime())).toString() + " " + trm);
// here the code to send back the message from nio socet to client
line mark with 100 add 2 space because there is a header with a short value that have the length of
the message to be readed by socket client
byte[] bytes = message.getBytes("ISO-8859-1");
writeLength = message.length();
//writeLength = bytes.length;
100 writeBuffer = ByteBuffer.allocate(writeLength + 2);
writeBuffer.putShort( (short)writeLength );
writeBuffer.put(message.getBytes()); // Para test
//this.writeBuffer.putChar('\n');
writeBuffer.flip();
// auxiliar methods
public String hexToASCII(String hex){
if(hex.length()%2 != 0){
System.err.println("requires EVEN number of chars");
return null;
}
StringBuilder sb = new StringBuilder();
//Convert Hex 0232343536AB into two characters stream.
for( int i=0; i < hex.length()-1; i+=2 ){
/*
* Grab the hex in pairs
*/
String output = hex.substring(i, (i + 2));
/*
* Convert Hex to Decimal
*/
int decimal = Integer.parseInt(output, 16);
sb.append((char)decimal);
}
return sb.toString();
}
private final String HEXES = "0123456789ABCDEF";
private final String HEX[] = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
private final String BIN[] = {"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"};
/*
* Convert binary to hex string
*/
public String binToHex(String bin) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < bin.length()-1 ; i += 4) {
sb.append(HEX[ArrayUtils.indexOf(BIN, bin.substring(i, (i + 4)))]);
}
return sb.toString();
}
You are mixing bytes and characters. There are dozens of ways to encode characters like ü and ö into bytes and different encodings take different amount of bytes per character.
DO NOT try to convert binary stream to string unless you know that the bytes represent textual information AND you know which encoding was used to convert the text into bytes in the first place. If the data is not a text string, DO NOT try to interpret it as a text string and just wish that every byte maps to something reasonable.
You can work directly with byte arrays or use e.g. java.nio.ByteBuffer. If there is a text string amongst the data, you can separately convert the peticular bytes into strings.
Your binary bitmap is getting mangled by character encoding conversions. There is no point in doing it that way. You can just convert from hex to byte[].
This code suggests the way:
String bitmapHex = "00112233445566778899aabbccddeeff";
String isoCode = "1200";
String data = "313030303030303031 and more";
byte[] bitmap = javax.xml.bind.DatatypeConverter.parseHexBinary(bitmapHex);
int datagramLength = 2 + isoCode.length() + bitmap.length + data.length();
ByteBuffer buffer = ByteBuffer.allocate(datagramLength);
buffer.order(ByteOrder.BIG_ENDIAN).putShort((short)datagramLength);
buffer.put(isoCode.getBytes(encodingName));
buffer.put(bitmap);
buffer.put(data.getBytes(encodingName));
byte[] output = buffer.array();

Categories