How to convert an Object to byte[]

How do I convert an object to a byte array without using the ObjectOutputStream?
I need to send an object over UDP socket which only works with byte[].

instead of serialisation for complex object i usexm and sax to transfer information over the network,
it works great
works nothing when transfering over the ORBWhen programming with a socket, sendTo is a standard function used in the connectionless protocol. I rewrote this function so as to be able to transmit objects. The following code example shows how to implement the send method in a Sender class:
import java.io.*;
import java.net.*;
public class Sender
{  public void sendTo(Object o, String hostName, int desPort) 
{    try   
{      InetAddress address = InetAddress.getByName(hostName);
ByteArrayOutputStream byteStream = new
ByteArrayOutputStream(5000);
ObjectOutputStream os = new ObjectOutputStream(new
BufferedOutputStream(byteStream));
os.flush();
os.writeObject(o);
os.flush();
//retrieves byte array
byte[] sendBuf = byteStream.toByteArray();
DatagramPacket packet = new DatagramPacket(
sendBuf, sendBuf.length, address, desPort);
int byteCount = packet.getLength();
dSock.send(packet);
os.close();
catch (UnknownHostException e)
System.err.println("Exception: " + e);
e.printStackTrace(); }
catch (IOException e) { e.printStackTrace();
The code listing below demonstrates how to implement a receive method in a Receiver class. Method recvObjFrom is for the receiver to receive the object. You can include this method in your code to receive runtime objects.
import java.io.*;
import java.net.*;
public class Receiver
{  public Object recvObjFrom() 
{    try
byte[] recvBuf = new byte[5000];
DatagramPacket packet = new DatagramPacket(recvBuf,
recvBuf.length);
dSock.receive(packet);
int byteCount = packet.getLength();
ByteArrayInputStream byteStream = new
ByteArrayInputStream(recvBuf);
ObjectInputStream is = new
ObjectInputStream(new BufferedInputStream(byteStream));
Object o = is.readObject();
is.close();
return(o);
catch (IOException e)
System.err.println("Exception: " + e);
e.printStackTrace();
catch (ClassNotFoundException e)
{ e.printStackTrace(); }
return(null); }
One may worry about the size of the byte array -- because when you construct ByteArrayOutputStream or ByteArrayInputStream, you have to specify the size of the array. Since you don't know the size of a runtime object, you will have trouble specifying that size. The size of a runtime object is often unpredictable. Fortunately, Java's ByteArrayInputStream and ByteArrayOutputStream classes can extend their sizes automatically whenever needed.
By
Sree Visveswaran

Similar Messages

  • How to convert an Integer to byte[] without lose data?

    How to convert an Integer to byte[] without lose data?

    I use the following to convert any java Object to a byte array
    public static byte[] getBytes(Object obj) throws java.io.IOException
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            oos.close();
            bos.close();
            byte [] data = bos.toByteArray();
            return data;
    }

  • How to convert matchcode objects to searchhelps.

    Hi,
    I had created search helps before but,
    We have a project in which we have matchcode objects. The client wants us to create
    searchhelps for those matchcode objects with the same name
    I am not getting how to convert matchcode objects to searchhelps.
    Regards,
    sarath.

    pick the object name and hit them in se11 search help row... that is a search help...
    parameter: p type x-x matchcode object <object_name>

  • How to convert Java Objects into xml?

    Hello Java Gurus
    how to convert Java Objects into xml? i heard xstream can be use for that but i am looking something which is good in performance.
    really need your help guys.
    thanks in advance.

    There are apparently a variety of Java/XML bindings. Try Google.
    And don't be so demanding.

  • How to convert character streams to byte streams?

    Hi,
    I know InputStreamReader can convert byte streams to character streams? But how to convert the character streams back to byte streams? Is there a Java class for that?
    Thanks in advance.

    When do you have to do this? There's probably another way. If you just start out using only InputStreams you shouldn't have that problem.

  • WD(ABAP) - How to convert PDF object to XML

    I know there is a way available to converting PDF object to XML in JAVA. However how to achieve this goal in ABAP?
    In Web Dynpro ABAP, I can bind a context attribute to the pdfSource property of interactive form element. There also should be method to able to convert the binary content of this attribute to XML format, right? Does anyone know it?
    Your help would be greatly appreciated.

    Hi all,
    As an extension to Fred's question, is it possible to later use the generated XML data and present it in a PDF template?  It used to be possible using the FDF format, but Adobe seem to have discontinued that. 
    My basic requirement is to send the form data to a third party in XML format and for them to be able to view it in human-readable format, preferably using a PDF as a template. 
    Is this possible?
    Thanks,
    Jonathan

  • How to convert an object to double

    how can i convert an Object into double?
    do i need to import anything?

    I think you mean, such a thing:
    Object obj;
    obj=new Double(3.14159);
    double value=obj.doubleValue();//possible
    obj=new Object();
    value=obj; //not possible!!!!!!!!!!!!!!
    In this case, the static type of obj is Object but the dynamic type is Double. Double is the "wrapper"-class for the variable-type double. For all variable-types is a wrapper-class existing. This is only for one reason that you can store "Values" within an Object Instance.
    Hope this helps
    chris

  • How to convert the Object into tonumber

    Hi all,
    How to convert a date in Object type into a number type.
    eg:
    Object EVENT_NUMBER = ADFContext.getCurrent().getSessionScope().get("SV_EVENT_NUMBER");
    Number LV_N_EVENT_NUMBER = EVENT_NUMBER.*toNumber();*
    I need to assign the value in number type to variable LV_N_EVENT_NUMBER.
    Thanks in advance
    C.Karukkuvel

    Hi,
    I am assuming you are using oracle.jbo.domain.Number.
    Is this what you need?
    Number num;
                try {
                    num = new Number(object);
                } catch (SQLException e) {
                }Gabriel.

  • How to convert a certificate from byte[] typeback to its original type

    Doing work about transfer Certificate through network using socket, after using
    Certificate.getEncode() convert it into byte[] type, then send through network, but
    at the receiver side, don't know how to convert the byte[] format back to the
    Certificate? Or there is a better way to transfer Certificate as a file through
    socket?

    If it is an X509 one:
    Certificates are instantiated using a certificate factory. The following is an example of how to instantiate an X.509 certificate:
    InputStream inStream = new FileInputStream("fileName-of-cert");
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate)cf.generateCertificate(inStream);
    inStream.close();

  • How to convert an Object into integer?

    Ho can v convert an object of type Object into integer data type?
    Object obj = null;
    integer int = _____________;
    plz do fill it up and help ASAP......

    Fortunately, Gosling was able to predict that his
    language would produce exceptions, so he gave usthe
    catch block, so we can magically make them goaway:
    > catch (Exception exc) {}You are
    probably not without knowing that empty catch blocks
    are considered to be bad practice.
    You should better do the following
    :catch(Exception exc) {
    throw new RuntimeException();
    ode]You turned your sarcasm detector off or something?? :-)

  • How to Convert Date Object at Universe Level with out Timestamp

    Hi,
    I have a Object  called "PCREGISTERDATE" at universe where the data type is date .but the dates are coming in the following format:9/26/2007 9:48:40 PM but i want to show the date as with out time stamp.
    how can i create a object by at universelevel which shoul show only date with out Time Stamp.
    please help me on this ASAP.
    Thanks & Regards,
    Kumar

    Please try below date fucntion:
    select convert(varchar(10),getdate(),101)  - this is for sybase
    syntex will change based on your source database.
    Thanks
    Ponnarasu .K

  • How to convert a integer into bytes!!!

    I am trying to pack the length of the data transamitted over a stream into 2 bytes (Each byte is a unsigned char in terms of 'C' language). When i am using the bytes in java any value greater than 127 is a negative number (I understand the very definition of 'byte' in java), my question is how to pack the length of the data the 'C' way still following Java rules??
    Example :: Length of the data is 168 say!
    the 2 bytes would be 0x00, 0x80 (the respective ascii values would be NULL, P) but with Java i get some thing different as we know??
    byte 1 = 00 and byte 2 = -88 ( i am not sure what would be the ascii equivalent of this??)
    Please help!

    For what it's worth:package ca.adaptor.util;
    * $Id: ByteUtil.java,v 1.6 2003/03/28 18:24:47 mike Exp $
    * Copyright (c) 2002 by Michael Coury
    *  This library is free software; you can redistribute it and/or
    *  modify it under the terms of the GNU Lesser General Public
    *  License as published by the Free Software Foundation; either
    *  version 2.1 of the License, or (at your option) any later version.
    *  This library is distributed in the hope that it will be useful,
    *  but WITHOUT ANY WARRANTY; without even the implied warranty of
    *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    *  Lesser General Public License for more details.
    *  You should have received a copy of the GNU Lesser General Public
    *  License along with this library; if not, write to the Free Software
    *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    * @author Michael Coury (mdc)
    * @created Sep 20, 2002
    * @version $Revision: 1.6 $, $Date: 2003/03/28 18:24:47 $
    public final class ByteUtil {
      private static final int  __NUM_BYTES_IN_LONG_   = 8;
      private static final int  __NUM_BYTES_IN_INT_    = 4;
      private static final int  __NUM_BYTES_IN_SHORT_  = 2;
      private static final int  __NUM_BITS_IN_BYTE_    = 8;
      private static final long __BYTE_MASK_           = 0xFF;
      /** PRIVATE CONSTRUCTOR */
      private ByteUtil() {}
                ///// ENCODE /////
       * Converts a number to its binary equivalent and returns that as a byte array
      public static final byte[] toBytes(final long aNum) {
        final byte[] ret = new byte[__NUM_BYTES_IN_LONG_];
        for(int i = 0; i < __NUM_BYTES_IN_LONG_; i++)
          ret[i] = (byte) (aNum >>> ((__NUM_BYTES_IN_LONG_ - 1 - i) * __NUM_BITS_IN_BYTE_));
        return ret;
       * Converts a number to its binary equivalent and returns that as a byte array
      public static final byte[] toBytes(final int aNum) {
        final byte[] ret = new byte[__NUM_BYTES_IN_INT_];
        for(int i = 0; i < __NUM_BYTES_IN_INT_; i++)
          ret[i] = (byte) (aNum >>> ((__NUM_BYTES_IN_INT_ - 1 - i) * __NUM_BITS_IN_BYTE_));
        return ret;
       * Converts a number to its binary equivalent and returns that as a byte array
      public static final byte[] toBytes(final short aNum) {
        final byte[] ret = new byte[__NUM_BYTES_IN_SHORT_];
        for(int i = 0; i < __NUM_BYTES_IN_SHORT_; i++)
          ret[i] = (byte) (aNum >>> ((__NUM_BYTES_IN_SHORT_ - 1 - i) * __NUM_BITS_IN_BYTE_));
        return ret;
       * Converts a number to its binary equivalent and returns that as a byte array
      public static final byte[] toBytes(final double aNum) {
        return toBytes(Double.doubleToRawLongBits(aNum));
       * Converts a number to its binary equivalent and returns that as a byte array
      public static final byte[] toBytes(final float aNum) {
        return toBytes(Float.floatToRawIntBits(aNum));
                ///// DECODE /////
       * Converts a byte array representing a long back to a long
      public static final long toLong(final byte[] aNum) {
        try {
          long ret = 0L;
          for(int i = 0; i < __NUM_BYTES_IN_LONG_; i++) {
            ret += ((long) aNum[i] & __BYTE_MASK_) << ((__NUM_BYTES_IN_LONG_ - 1 - i) * __NUM_BITS_IN_BYTE_);
          return ret;
        catch(Exception e) {
          throw new NumberFormatException("Invalid number of bytes for long.  Found: " + aNum.length
                                          + " Required: " + __NUM_BYTES_IN_LONG_);
       * Converts a byte array representing an int back to an int
      public static final int toInt(final byte[] aNum) {
        try {
          int ret = 0;
          for(int i = 0; i < __NUM_BYTES_IN_INT_; i++)
            ret += (aNum[i] & __BYTE_MASK_) << ((__NUM_BYTES_IN_INT_ - 1 - i) * __NUM_BITS_IN_BYTE_);
          return ret;
        catch(Exception e) {
          throw new NumberFormatException("Invalid number of bytes for int.  Found: " + aNum.length
                                          + " Required: " + __NUM_BYTES_IN_INT_);
       * Converts a byte array representing a short back to a short
      public static final short toShort(final byte[] aNum) {
        try {
          short ret = 0;
          for(int i = 0; i < __NUM_BYTES_IN_SHORT_; i++)
            ret += (aNum[i] & __BYTE_MASK_) << ((__NUM_BYTES_IN_SHORT_ - 1 - i) * __NUM_BITS_IN_BYTE_);
          return ret;
        catch(Exception e) {
          throw new NumberFormatException("Invalid number of bytes for short.  Found: " + aNum.length
                                          + " Required: " + __NUM_BYTES_IN_SHORT_);
       * Converts a byte array representing a double back to a double
      public static final double toDouble(final byte[] aNum) {
        return Double.longBitsToDouble(toLong(aNum));
       * Converts a byte array representing a float back to a float
      public static final float toFloat(final byte[] aNum) {
        return Float.intBitsToFloat(toInt(aNum));
                ///// SHIFTING /////
      public static final byte shiftRightUnsigned(final byte b, final int shift) {
        return (shift > __NUM_BITS_IN_BYTE_) ? 0x00 : (byte) ((b & 0xFF) >>> shift);
      public static final byte shiftRight(final byte b, final int shift) {
        return (byte) (b >> shift);
      public static final byte shiftLeft(final byte b, final int shift) {
        return (shift > __NUM_BITS_IN_BYTE_) ? 0x00 : (byte) (b << shift);
    }

  • How to convert data read in byte to decimal number?

    The following are a source code to read from a serial port, but i can't convert the data that i read to decimal number and write it on a text file.....can anyone kindly show me how to solve it? thanks
    import javax.comm.*;
    import java.io.*;
    import java.util.*;
    public class Read implements Runnable, SerialPortEventListener {
         // Attributes for Serial Communication
         static Enumeration portList;
         static CommPortIdentifier portId;
         SerialPort serialPort;
         static OutputStream outputStream;
         InputStream inputStream;
         Thread readThread;
         public static void main(String s[])
         portList=CommPortIdentifier.getPortIdentifiers();
         while(portList.hasMoreElements())
              portId=(CommPortIdentifier)portList.nextElement();
              if(portId.getPortType()==CommPortIdentifier.PORT_SERIAL)
                   if(portId.getName().equals("COM1"))
                        System.out.println( portId.getName());
                        Read ss=new Read();
              }     // end of while
    }          // end of main
    public Read()     {
    try{
              serialPort=(SerialPort)portId.open("Read", 2000);
    catch(PortInUseException e)     {}
         try{
              inputStream=serialPort.getInputStream();
              System.out.println(inputStream);
    catch(IOException e)     {}
         try{
              serialPort.addEventListener(this);
    catch(Exception e)     {}
              serialPort.notifyOnDataAvailable(true);
         try{
              serialPort.setSerialPortParams(9600,
              SerialPort.DATABITS_8,
              SerialPort.STOPBITS_1,
              SerialPort.PARITY_NONE);
              }catch(UnsupportedCommOperationException e)     {}
              readThread=new Thread(this);
              readThread.start();
         }//end of constructor
         public void run()
              try     {
                   Thread.sleep(200);
              }catch(InterruptedException e)     {}
         public void serialEvent(SerialPortEvent event)
              switch(event.getEventType())
                   case SerialPortEvent.BI:
                   case SerialPortEvent.OE:
                   case SerialPortEvent.FE:
                   case SerialPortEvent.PE:
                   case SerialPortEvent.CD:
                   case SerialPortEvent.CTS:
                   case SerialPortEvent.DSR:
                   case SerialPortEvent.RI:
                   case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                   break;
                   case SerialPortEvent.DATA_AVAILABLE:
                   byte[]readBuffer=new byte[8];
                   try{
                        while(inputStream.available()>0)
                             int numBytes=inputStream.read(readBuffer);
                             //System.out.println("hello");
                        System.out.print(new String(readBuffer));
                        }catch(IOException e)     {}
                   break;
                   }     // end of switch
                   try     {
                        inputStream.close();
                        }catch(Exception e5)     {}
         }          // end of serialEvent

    Is it a float or a double?
    For a float, the decimal should be 4 bytes (small numbers like 1.1 start with the byte 0x40). Convert these 4 bytes to an int, using byte-shifting would probably be easiest.
    int value = ((b3 << 24) + (b2 << 16) + (b1 << 8) + b0);//b# are bytesNow to convert it to a float, use
    Float.intBitsToFloat(value);Now if you want double percision, You will have 8 bytes instead of 4, and need to be converted to a long instead of an int through byte-shifting. Then use Double.longBitsToDouble(long bits) to get the double

  • How to convert java object to xml?

    Is JAXB the only way to do so?
    Can somebody help me?
    I have tried for almost a week,
    but I am failed all the time.

    Sax would be the best way to do it,
    Create a class that implements the org.xml.sax.XMLReader interface. Fire events at its ContentHandler (like open tag, element content characters, and close tag) and it can be used to create a javax.xml.transform.sax.SAXSource.
    I learnt how to do this by looking at example code that comes with the pache FOP project. They have a class which is "converted" to XML, and that output is fed through a transformation. I cribbed their code and used it in mine. Including their helper classes AbstractObjectReader and EasyGenerationContentHandlerProxy which help a lot.
    Of course you never see the XML from the object, that's just a transitional form, but you COULD output that if you wanted. Take a look at http://xml.apache.org/fop/ - the code is bundled with the installation under the "examples" directory.

  • How to convert UIView object to NSData and vise-versa  for saving it in database using sqlite

    I am using sqlite for my project which stores all the data including text fields , id , and one UIVIew object in a column having BLOB datatype .
    Now while retriving the data i use
    const char *raw = sqlite3_column_blob(selectstmt, 3);
    int rawLen = sqlite3_column_bytes(selectstmt, 3);
    NSData *data = [NSData dataWithBytes:raw length:rawLen];
      view =[NSKeyedUnarchiver unarchiveObjectWithData:data];
    where data is NSData obj n view is UIView obj ,
    also while inserting data  i use ,
    NSData *data=[[NSData alloc]init];
        data=[NSKeyedArchiver archivedDataWithRootObject:view];
       // [data dataForView:notes.view];
        sqlite3_bind_blob(updateStmt, 2, [data bytes], [data length], SQLITE_TRANSIENT);
    But this is not working properly ...  the Data object is giving some length,
    while using the view the view object is null
    is there any other solution to do the same ?

    There's a ton of information here: [http://www.json.org/] and I can't believe you didn't find that site yourself.

Maybe you are looking for

  • Problem cloning your old hard drive to a new hard drive / ssd

    I followed the procedure (from Bimmer, and several googled results), on cloning a boot disk for my macbook pro 17" (A1229), circa 2007, and I have a cloned SSD (Kingston ssdnow v300/240GB) that boots in an external drive, but not internally.  The ori

  • How to change the Schema (DB2, Oracle) in CommandTable at run time

    Dear all, I have a problem as below: I have created report with CommandTable, then I am using Java and CRJ 12 to export data. So how to change the SCHEMA in CommandTable?  Please help me on this. Ex: CommandTable is SELECT * from SCHEMA.TableA, SCHEM

  • Help : Message Driven bean seeing the same message multiple times.

    ( We are using weblogic 8.1 on Solaris ) We have a bunch of message driven beans with the transaction type as 'Container' and the acknowledge-mode mode as auto-acknowledge. They are consuming messages from a weblogic Queue ( javax.jms.Queue ). The MB

  • [SOLVED] Disable/remove NetworkManager, and use netctl

    Hello! I just installed arch linux and gnome shell with only few applications. I was using netctl-auto, which I enabled using systemctl during the installation. Everything was worked fine, until I installed the packages tlp and tlp-rdw. They pulled i

  • 2 lenses in 1 converter

    stumbled upon this website talking about 2 lenses in 1. have you seen this wide angle macro lens.  i have an entry level nikon d40 and have been pondering to get some lenses.  Due to budget, im trying get a lens that gets me the range but not too exp