2016-05-20 267 views
0

我正在使用消息api在智能手機和智能手錶之間發送消息。由於它只能將字節數組作爲數據發送,因此我希望將對象轉換爲字節數組,同時在接收時發送和反轉轉換。如何將Android對象轉換爲字節數組並返回?

我已經使用了我從互聯網上獲得的下面的代碼。但我得到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; 
    } 
+0

對象是可串行化的嗎?說,爲什麼不讓你的方法接收'Serializable obj'呢? – Budius

+0

看看這裏:http://stackoverflow.com/questions/2836646/java-serializable-object-to-byte-array – Konstantin

+0

非常感謝鏈接。使用ApacheUtils爲我工作: 序列化: byte [] data = SerializationUtils.serialize(yourObject); 反串行化: YourObject yourObject =(YourObject)SerializationUtils.deserialize(byte [] data) – NewOne

回答

0
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(); 
} 

試一下這個可能它會爲你工作,它會在下載文件夾中的文件存儲在您的智能手機。

相關問題