今晚上在編寫udp傳輸文件的時候發現無法用JSON傳輸字節數組,試了很多種辦法都會報錯,最后查資料找到了Base64這個類,這個類可以將字節數組轉為字符串,在JSON中傳輸以后可以再轉化為字節數組。
寫個小例子如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
package
test;
import
java.util.Base64;
public
class
testStringAndbyte
{
public
static
void
main(String[] args)
{
// TODO Auto-generated method stub
byte
[] s1 = {
0
,
1
,
0
};
String FileBuf = Base64.getEncoder().encodeToString(s1);
System.out.println(FileBuf);
byte
[] s2 = {};
s2 = Base64.getDecoder().decode(FileBuf);
for
(
int
i =
0
;i<s2.length;i++)
{
System.out.print(s2[i]);
}
}
}
|
運行結果如下所示:
這樣的話就可以使用JSON格式傳送字節數組了。