加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MySql教程 > 正文

java – 将ArrayList转换为字节数组

发布时间:2020-12-11 23:37:51 所属栏目:MySql教程 来源:网络整理
导读:我有一个代码,我将数组列表转换为字节数组,然后将该字节数组保存为MySQL数据库中的BLOB.以下是代码: Object temp = attributes.get(columnName);if (temp instanceof List temp != null) { List extraAttributes = (ArrayList) temp; resultStmt.setBytes(c

我有一个代码,我将数组列表转换为字节数组,然后将该字节数组保存为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.

我正在读取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 [].
一种合理的方法是使用像DataOutputStream这样的UTF-8编码为列表中的每个字符串.对于字符串,它为UTF-8编码的长度写入2个字节,后跟UTF-8字节.如果您不在另一端使用Java,这将是可移植的.以下是编码和解码ArrayList的示例:

// example input list
List

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读