您需要定義一種格式。您有以下
byte[] avroBinaryValue = os.toByteArray();
String schemaName = "DEMOGRAPHIC";
long lastModifiedDate = 1379811105109L;
我想avroBinaryValue
可以可變長度等都可以schemaName
。對於所有的意圖和目的,lastModifiedDate
適合一個很長的,即。 8個字節。
如果你想序列化這個(除了使用Serializable
),你將不得不使用一種特定的格式來告訴你你正在閱讀什麼以及什麼時候停止閱讀它。例如,
Offset Length (in bytes) Purpose
0 4 - length of avroBinaryValue array
4 X - avroBinaryValue array
4+X 4 - length of of schemaName byte array
4+X+4 Y - schemaName byte array
4+X+4+Y 8 - value of lastModifiedDate
還決定是否要big-endian或小端字節順序。
因此,你按照格式描述寫下你的三個字段,並以相同的方式閱讀它。
下面是在內存中完成一個例子,其中os
是String
(爲簡單起見)一
public static void main(String[] args) throws Exception {
String os = "whatever os is";
byte[] avroBinaryValue = os.getBytes();
String schemaName = "DEMOGRAPHIC";
long lastModifiedDate = 1379811105109L;
byte[] schemaNameBytes = schemaName.getBytes();
ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(byteOs);
out.writeInt(avroBinaryValue.length);
out.write(avroBinaryValue);
out.writeInt(schemaNameBytes.length);
out.write(schemaNameBytes);
out.writeLong(lastModifiedDate);
// write done
byte[] allWrittenBytes = byteOs.toByteArray();
DataInputStream in = new DataInputStream(new ByteArrayInputStream(allWrittenBytes));
int sizeAvro = in.readInt();
avroBinaryValue = new byte[sizeAvro];
in.read(avroBinaryValue, 0, sizeAvro);
int sizeSchema = in.readInt();
schemaNameBytes = new byte[sizeSchema];
in.read(schemaNameBytes, 0, sizeSchema);
lastModifiedDate = in.readLong();
// read done
System.out.println(new String(avroBinaryValue));
System.out.println(new String(schemaNameBytes));
System.out.println(lastModifiedDate);
}
它打印
whatever os is
DEMOGRAPHIC
1379811105109
我明白你想節省空間,但將每個字段寫入其自己的列或使用標準形式可能會更好不喜歡XML或JSON來序列化你的領域。
如果您要將數據寫入磁盤並再次讀取,您可以使用DataOutputStream和DataInputStream(當然還有FileOutputStream和FileInputStream)。 – jtahlborn
我將寫入Cassandra數據庫,這就是爲什麼我說磁盤.. – AKIWEB