上一篇文章,我們已經提出一個方案,先把對象轉成json格式的文件,然後再把json格式的文本轉成二進制傳輸。現在介紹比較專業的數據傳輸方式,對象直接編碼爲二進制。
首先,我們先來了解一下數據的二進制編碼。對所有基本數據類型都可以轉yte[],例如:long -> byte[8] int -> byte[4] short -> byte[2] double -> byte[8] float -> byte[4] boolean ->byte[1] ,在Java中,我們可以ByteBuffer這個類對數據進行二進制編碼,用法如下所示:
ByteBuffer buf = ByteBuffer.allocate(1000);
//放入數據
buf.putInt(1234);
buf.putDouble(33.44);
//查看編碼後的結果
int size = buf.position();//已經編碼的字節數
byte[] array = buf.array();//獲得ByteBuffer的內部數組
上面是編碼的過程,那麼如何對其進行解碼呢,上面我們放入一個int類型和一個double類型的數據,解碼的時候調用get方法將其取出即可,代碼如下:
buf.getInt();
buf.getDouble();
我們講完數據的二進制編碼,下面我們說說如何將對象進行而二進制編碼,複雜對象的二進制,就是把它的各個字段進行二進制編碼,例如有如下的對象:
public class Student
{
public int id;
public String name;
public boolean sex;
public String cellphone;
public Student()
{
}
public Student(int id , String name, boolean sex, String cellphone)
{
this.id = id;
this.name = name;
this.sex = sex;
this.cellphone = cellphone;
}
@Override
public String toString()
{
return "學號: " + id
+ ",姓名: " + name
+ ",性別: " + ( sex ? "男": "女")
+ ",手機: " + cellphone
;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public boolean isSex()
{
return sex;
}
public void setSex(boolean sex)
{
this.sex = sex;
}
public String getCellphone()
{
return cellphone;
}
public void setCellphone(String cellphone)
{
this.cellphone = cellphone;
}
}
我們將其進行二進制編碼,就是把各個字段進行二進制編碼,具體編碼和解碼如下:
package my;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
public class Test
{
public static int encode(Student stu , byte[] data) throws UnsupportedEncodingException
{
ByteBuffer bbuf = ByteBuffer.wrap(data);
//id編碼
bbuf.putInt(stu.id);
//name
byte[] strbuf = stu.name.getBytes("UTF-8");
bbuf.putShort((short)strbuf.length);
bbuf.put(strbuf);
//sex
bbuf.put(stu.sex?(byte)1:(byte)0);
//cellphone
strbuf = stu.cellphone.getBytes("UTF-8");
bbuf.putShort((short)strbuf.length);
bbuf.put(strbuf);
return bbuf.position();
}
public static Student decode(byte[] data , int n) throws UnsupportedEncodingException
{
ByteBuffer bbuf = ByteBuffer.wrap(data);
Student stu = new Student();
//id
stu.id = bbuf.getInt();
//name
byte[] strbuf = new byte[1000];
int strlen = bbuf.getShort();//
bbuf.get(strbuf, 0, strlen);
stu.name = new String(strbuf ,0 , strlen , "UTF-8");
//sex
stu.sex = (bbuf.get() != 0);
strlen = bbuf.getShort();
bbuf.get(strbuf, 0, strlen);
stu.cellphone = new String(strbuf , 0 , strlen , "UTF-8");
return stu;
}
public static void main(String[] args) throws UnsupportedEncodingException
{
//
byte[] data = new byte[1000];
//
Student s1 = new Student();
s1.id = 20190001;
s1.name = "小明";
s1.sex = true;
s1.cellphone = "13810012345";
// encodeֵ
int n = encode(s1, data);
Student s2 = decode(data, n);
System.out.println(s2.toString());
System.out.println("\nexit");
}
}
以上得到對象的二進制的編碼和解碼,然後就可以進行數據的傳輸。