Pour object in byteArray

i has a function

   public static Object receviceSigAndData (Socket s) {
       byte[] data = null;
       try {
            DataInputStream din2 = new DataInputStream(s.getInputStream());
            int sig_len = 0;
            sig_len = din2.readInt();
            byte[] sig = new byte[sig_len];
            din2.readFully(sig);
            int data_len = 0;
            data_len = din2.readInt();
            data = new byte[data_len];     
            dsa.update(data);


       } catch (IOException ioe) {
                ioe.printStackTrace();
       } catch (Exception e) {
                e.printStackTrace();
       }

       return (Object)data;
   }

The function returns an object, if the object is an array of bytes, how can I make an object byte[]?

byte[] b = (?)receviceSigAndData (socket);

thank

+3
source share
2 answers

Here are two helper methods that let you serialize and deserialize byte arrays as objects.

public static Object deserializeBytes(byte[] bytes) throws IOException, ClassNotFoundException
{
    ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytes);
    ObjectInputStream ois = new ObjectInputStream(bytesIn);
    Object obj = ois.readObject();
    ois.close();
    return obj;
}


public static byte[] serializeObject(Object obj) throws IOException
{
    ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bytesOut);
    oos.writeObject(obj);
    oos.flush();
    byte[] bytes = bytesOut.toByteArray();
    bytesOut.close();
    oos.close();
    return bytes;
}
+3
source

Looking at your code:

  • you are not converting the return value to Object: since it is an upcast, it is implicitly executed (a byte[]statically as well Object)
  • you can easily distinguish Objectfrom byte[]using a specific downcast:byte[] a = (byte[])obj
  • , , Object, , . Object - , . byte[], byte[] type
+8

All Articles