[英]Convert ArrayList to byte array
我有一個代碼,我將數組列表轉換為字節數組,然后將該字節數組保存為 MySQL 數據庫中的 BLOB。 以下是代碼:-
Object temp = attributes.get(columnName);
if (temp instanceof List && temp != null) {
List extraAttributes = (ArrayList) temp;
resultStmt.setBytes(currentIndex, createByteArray(extraAttributes));
createByteArray
方法定義如下:
private byte [] createByteArray( Object obj)
{
byte [] bArray = null;
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream objOstream = new ObjectOutputStream(baos);
objOstream.writeObject(obj);
bArray = baos.toByteArray();
}
catch (Exception e)
{
TraceDbLog.writeError("Problem in createByteArray", e);
}
return bArray;
}
好吧,上面的代碼是早先編寫的,用於將 HashMap 寫入 BLOB,如果 HashMap 到 BLOB,我正在使用相同的代碼將 ArrayList 轉換。
當我讀取 blob 時,讀取代碼中出現的問題。
private Object readBytes (ResultSet rs, String columnName)
throws SQLException
{
ObjectInputStream ois = null;
byte [] newArray;
Object obj = null;
try
{
newArray = rs.getBytes(columnName);
ois = new ObjectInputStream (new ByteArrayInputStream(newArray));
obj = ois.readObject ();
}
在讀取部分,對象不是作為 hasMap 的 arrayList 出現的,並且在 eclipse 的調試透視圖中,eclipse 也無法檢查即將到來的對象。
我也嘗試將對象類型轉換為 List,但仍然沒有成功獲得正確的響應。 請告訴我讀/寫上述BLOB是否有任何缺陷。
我添加了用於將ArrayList轉換為 byte[] 的示例編碼。
一種合理的方法是使用 UTF-8 編碼,就像 DataOutputStream 對列表中的每個字符串所做的那樣。 對於字符串,它為 UTF-8 編碼的長度寫入 2 個字節,然后是 UTF-8 字節。
如果您不在另一端使用 Java,這將是可移植的。 下面是一個對 ArrayList 進行編碼和解碼的示例:
// example input list
List<String> list = new ArrayList<String>();
list.add("foo");
list.add("bar");
list.add("baz");
// write to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos);
for (String element : list) {
out.writeUTF(element);
}
byte[] bytes = baos.toByteArray();
// read from byte array
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
DataInputStream in = new DataInputStream(bais);
while (in.available() > 0) {
String element = in.readUTF();
System.out.println(element);
}
最簡單的方法是將其轉換為json字符串,然后再轉換為字節
Gson gson = new Gson();
Type type = new TypeToken<List<Alarm>>() {}.getType();
String json = gson.toJson(list, type);
byte[] bytes = json.getBytes();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.