【问题标题】:How to convert an android object into a byte array and do it back?如何将android对象转换为字节数组并返回?
【发布时间】:2016-05-20 18:27:13
【问题描述】:

我正在使用消息 api 在智能手机和智能手表之间发送消息。由于它只能发送字节数组作为数据,我想在发送时将对象转换为字节数组,并在接收时反转转换。

我使用了以下从互联网上获得的代码。但我得到了 java.io.NotSerializableException。有没有更好的方法呢?

我的对象将有一个字符串值和一个 android 包。两者都需要从一个设备发送并在另一端接收。

public static byte[] toByteArray(Object obj) throws IOException {
        byte[] bytes = null;
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray();
        } finally {
            if (oos != null) {
                oos.close();
            }
            if (bos != null) {
                bos.close();
            }
        }
        return bytes;
    }

public static Event toObject(byte[] bytes) throws IOException, ClassNotFoundException {
        Event obj = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {
            bis = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(bis);
            obj = (Event) ois.readObject();
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (ois != null) {
                ois.close();
            }
        }
        return obj;
    }

【问题讨论】:

  • 你的对象是可序列化的吗?就是说,为什么不让你的方法接收Serializable obj呢?
  • 非常感谢您的链接。使用 ApacheUtils 对我有用: 序列化:字节 [] 数据 = SerializationUtils.serialize(yourObject);反序列化:YourObject yourObject = (YourObject) SerializationUtils.deserialize(byte[] data)

标签: android serialization wear-os android-bundle


【解决方案1】:
 public void toByteArray(Object obj) throws IOException {
    FileOutputStream outputstream = new FileOutputStream(new File("/storage/emulated/0/Download/your_file.bin"));
    outputstream.write((byte[]) obj);
    Log.i("...","Done");
    outputstream.close();
}

试试这个可能对你有用,它会将你的文件存储在智能手机的下载文件夹中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-21
    • 2019-03-09
    • 1970-01-01
    • 2014-10-26
    • 2016-06-22
    • 2011-02-23
    • 2013-06-12
    • 1970-01-01
    相关资源
    最近更新 更多