Object to byte [] and byte [] to Object

Hi,
I am quite new to java and need some help. My question is how can I convert an Object to byte [] and convert back from byte [] to Object.
I was thinking of something like:
From object to byte []
byte [] object_byte=object.toString().getBytes();
When I try to do:
String obj_string=object_byte.toString();
But obj_string is not even equal to object.toString().
Any suggestions?
Thanks

// byte[] to Object
byte[] b = new byte[]{1};
Object o = (new ObjectInputStream(new ByteArrayInputStream(b))).readObject();
// Object to byte[]
Object o = new Object();
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();    
ObjectOutputStream objStream = new ObjectOutputStream(byteStream);       
objStream.writeObject(o);  
byte[] b = byteStream.toByteArray();

Similar Messages

  • Byte [] to Object and Object to byte[]

    Hi,
    I am quite new to java and need some help. My question is how can I convert an Object to byte [] and convert back from byte [] to Object.
    I was thinking of something like:
    From object to byte []
    byte [] object_byte=object.toString().getBytes();
    When I try to do:
    String obj_string=object_byte.toString();
    But obj_string is not even equal to object.toString().
    Any suggestions?
    Thanks

    well nnneil, if you try to convert and Object into a byte[] in that way you only convert the string representation of the object in bytes.
    If you remenber an object is more than a simple bytes stream, an object have Class, Methods, Attributes and other things, if you wanna, you can use serializable to convert your object in a bytes stream.
    Or if your problem if pass something like {0x01,0x02,0x0f,...} in an object you can use a simple casting over your variable.
    try with this:
    public class Main
    public static void main(String[] args)
    try
    byte[] bs = {0x00,0x00,0x00};
    Object o = (Object)bs;
    System.out.print("Object:[" + o.toString() + "]");
    System.out.print("<- That does not equals to ->");
    int i = 0;
    while(i < bs.length)
    System.out.print("[" + bs[i++] + "]");
    catch(Exception e){
    e.printStackTrace();
    output is: Object:[[B@df6ccd]<- That does not equals to ->[0][0][0]
    if you see [B@df6ccd is the internal represent of bs object.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Passing serialized object and data as byte stream over same stream

    I am writing a chat program, I am keeping online user List as Vector A would like to pass online user List to client as Vector object also the client message is sended as byte stream. Is it possible to pass object and data as byte stream over the same stream.

    I am writing a chat program, I am keeping online user
    List as Vector A would like to pass online user List
    to client as Vector object also the client message is
    sended as byte stream. Is it possible to pass object
    and data as byte stream over the same stream.Why are you sending the client message as a byte stream?
    String seems a much more logical type. I would assume that you're reading strings from one client, and printing them on the others. If you translate to bytes in the middle, you're going to have to ensure that you decode those streams correctly on the other side.
    And if I were implementing this, I probably wouldn't send the raw Vector or List ... instead, I'd create a Message object, which wraps the Vector/String, and a MessageDispatcher interface, which the client implements to handle incoming messages.

  • I've tried to convert the obkect into bytes and store it. But while retreiving it using JNDI, its giving me an object. That's not the object I need.

     

    You must convert and store the object into Base64. On read of the attribute convert from Base64 back into binary.

  • Object stream and byte array conversion

    Hello everyone,
    I am wondeirng how to convert an ObjectInputStream to a byte array, then convert the array back to ObjectInputStream -- should I convert the array back to ObjectOutputStream other than ObjectInputStream?
    Any sample codes?
    thanks in advance,
    George

    Isn't it the other way around? You can't do this directly:
    ObjectInputStream ois = ...;
    ByteArrayInputStream bais = new ByteArrayInputStream(ois);(but you can do it indirectly), but you can do this:
    ByteArrayInputStream bais = ...;
    ObjectInputStream ois = new ObjectInputStream(bais);

  • How can I convert an array off byte into an Object ?

    Hi folks...
    I�m developing an application that comunicates a PDA and a computer via Wi-Fi. I�m using a DataStream ( Input and Output ) to receive / send information from / to the computer. Most off the data received from him is in the byte[] type...
    How can I convert an array off byte ( byte[] ) into an Object using MIDP 2.0 / CLDC 1.1 ?
    I found on the web 2 functions that made this... but it uses a ObjectOutputStream and ObjectInputStream classes that is not provided by the J2ME plataform...
    How can I do this ?
    Waiting answers
    Rodrigo Kerkhoff

    There are no ObjectOutputStream and ObjectInputStream classes in CLDC. You must know what you are writing to and reading from the DataStream. You should write the primitives like int, String to the DataOutputstream at one end and read those in exactly the same sequence at the outher end using readInt(), readUTF() methods.

  • How can i convert an object to stream of chars or bytes?

    how can i convert an object to stream of chars or bytes?

    One way is the serialization mechanism. There are examples and explanations of it in the Java tutorial: http://java.sun.com/docs/books/tutorial/essential/io/serialization.html

  • How can i convert object to byte array very*100 fast?

    i need to transfer a object by datagram packet in embeded system.
    i make a code fallowing sequence.
    1) convert object to byte array ( i append object attribute to byte[] sequencailly )
    2) send the byte array by datagram packet ( by JNI )
    but, it's not satisfied my requirement.
    it must be finished in 1ms.
    but, converting is spending 2ms.
    network speed is not bottleneck. ( transfer time is 0.3ms and packet size is 4096 bytes )
    Using ObjectOutputStream is very slow, so i'm using this way.
    is there antoher way? or how can i improve?
    Edited by: JongpilKim on May 17, 2009 10:48 PM
    Edited by: JongpilKim on May 17, 2009 10:51 PM
    Edited by: JongpilKim on May 17, 2009 10:53 PM

    thanks a lot for your reply.
    now, i use udp socket for communication, but, i must use hardware pci communication later.
    so, i wrap the communication logic to use jni.
    for convert a object to byte array,
    i used ObjectInputStream before, but it was so slow.
    so, i change the implementation to use byte array directly, like ByteBuffer.
    ex)
    public class ByteArrayHelper {
    private byte[] buf = new byte[1024];
    int idx = 0;
    public void putInt(int val){
    buf[idx++] = (byte)(val & 0xff);
    buf[idx++] = (byte)((val>>8) & 0xff);
    buf[idx++] = (byte)((val>>16) & 0xff);
    buf[idx++] = (byte)((val>>24) & 0xff);
    public void putDouble(double val){ .... }
    public void putFloat(float val){ ... }
    public byte[] toByteArray(){ return this.buf; }
    public class PacketData {
    priavte int a;
    private int b;
    public byte[] getByteArray(){
    ByteArrayHelper helper = new ByteArrayHelper();
    helper.putInt(a);
    helper.putInt(b);
    return helper.toByteArray();
    but, it's not enough.
    is there another way to send a object data?
    in java language, i can't access memory directly.
    in c language, if i use struct, i can send struct data to copy memory by socket and it's very fast.
    Edited by: JongpilKim on May 18, 2009 5:26 PM

  • How to flush the loaded bytes of a Sound object

    Hi all,
    I've now been looking for a solution to my problem for quite
    a while now, but so far without any success, so I thought I'll give
    this forum a try.. maybe someone in here can help ;-)
    Ok here's the deal: I'm trying to create a simple audio
    player in flex that is able to play mp3 audio streams. I'm not
    looking for a solution that works with an FMS (Flash Mediaserver)
    and I do also not need code that shows me how to play a remote mp3
    file (which of course is also some sort of streaming streaming). I
    have an icecast internet radio server which is streaming a constant
    flow of mp3 encoded data. I can connect to that stream with
    standard media players like winamp or mplayer.
    I've been playing around with the
    URLRequest-SoundLoaderContext-Sound-SoundChannel-combo and tried
    many different combinations, but somehow the Sound object won't let
    go of the bytes it already played. The Sound.bytesLoaded will just
    keep increasing and my memory will just keep being eaten by the
    Flashplayer. Is there any way to free that memory again without
    having to destroy the Sound object? Or if I have to destroy it, how
    do I make sure that the user doesn't realize that I just switched
    the old Sound object with a fresh and empty one?
    I was also trying to get a NetConnection-NetStream-combo to
    play my stream, but here I failed even sooner: Even though the
    NetStream seems to be receiving the data from my server (Firefox
    states that it is receiving data after I invoke
    NetStream.play(url_to_stream)) I'm not able to get that data to
    come out of my speakers. I just can't hear anything :-(
    I'm pretty new to flex, as and flash, so please forgive me my
    ignorance ;) I really tried to figure this one out for about 3 days
    now..
    I'd be very grateful for any hints or advice :-)
    cheers,
    Lorenz
    Edit: oh yeah right: I don't know if this is too obvious, but
    I'm using flex3 :-)

    kurusaki wrote:
    i need to get the serial number of a X509Certificate
    the getSerialNumber() methode of X509Certificat return an BigInteger then can see in (windows application) or in the debuger of eclipse that the serial number is coded in HEXA
    how i can getting it in HEXA.
    If you look at the Javadoc for BigInteger you will see a toString() method that allows one to specify the radix. Hex is just radix 16.

  • Convery byte[] into a object

    i have a byte[] which I have got from DB. I want to convert it into a object before returning it from a method. There is a wraaper class for byte i.e. Byte. But I am not sure tha how to convert a byte[] into an Object.
    Thanks!!

    georgexu316 wrote:
    corlettk wrote:
    georgexu316 wrote:
    If you know what you are doing, you can perform an implicit conversion by casting the byte.
    byte byteData = new byte();
    Object newObj = (Object) byteData;
    Umm.. Dude, a byte array is-an Object. In Java you don't ever need to explicitly up-cast... but (in order to actually use it as a byte array) you do have to explicitly down-cast it.
    For example:
    package forums;
    class AByteArrayIsAnObject
    public static void main(String[] args) {
    try {
    Object bytes = "Hello World!".getBytes(); // returns a reference to a newly created byte-array-object
    System.out.println( new String((byte[])bytes) );
    } catch (Exception e) {
    e.printStackTrace();
    Well, the person asked to convert it into an Object, maybe he needs it as a object to pass it through another parameter of another method. Even though byte is an extension of Object and you can use all of Object's methods, it wouldn't pass through a parameter of a method that specifies an object.Ummm... Wanna bet?
    package forums;
    class AByteArrayIsAnObjectTest
      public static void main(String[] args) {
        try {
          println(new String((byte[])getBytes("Hello World!")));
        } catch (Exception e) {
          e.printStackTrace();
      private static Object getBytes(String s) {
        return s.getBytes();
      private static void println(Object o) {
        System.out.println(String.valueOf(o));
    }

  • Display an object of Image type or Byte Array

    Hi, lets say i got an image stored in the Image format or byte[]. How can i make it display the image on the screen by taking the values in byte array or Image field?

    Thanks rahul,
    The thing is, i am generating a chart in a servlet
    and setting the image in the form of a byte [] to the
    view bean ( which is binded to the jsp, springs
    framework ). The servlet would return the view bean
    to the jsp and in the jsp, i am suppose to print this
    byte array so as to give me the image..
    I hope this makes sense.. pls help me ou!Well letme see if i got tht right or not,
    you are trying to call Your MODEL (Business layer / Spring Container) from a servlet and you are expressing that logic in form of chart (Image) and trying to save it as a byte array in a view bean and you want to print /display that as an image in a jsp (After Servlet fwd / redirect action) which includes other data using a ViewBean.
    If this is the case...
    As the forwaded JSP can include both image and Textual (hypertext too)..we can try a work around hear...Lets dedicate a Servlet which retreives byte [] from a view bean and gives us an image output. hear is an example and this could be a way.
    Prior to that i'm trying to make few assumptions here....
    1).The chart image which we are trying to express would of format JPEG.
    2).we are trying to take help of<img> tag to display the image from the image generating servlet.
    here is my approach....
    ViewBean.java:
    ============
    public class ViewBean implements serializable{
    byte piechart[];
    byte barchart[];
    byte chart3D[];
    public ViewBean(){
    public byte[] getPieChart(){
    return(this.piechart);
    public byte[] getBarChart(){
    return(this.barchart);
    public byte[] get3DChart(){
    return(this.chart3D);
    public void setPieChart(byte piechart[]){
    this.piechart = piechart;
    public void setBarChart(byte barchart[]){
    this.barchart = barchart;
    public void set3DChart(byte chart3D[]){
    this.chart3D = chart3D;
    }ControllerServlet.java:
    =================
    (This could also be an ActionClass(Ref Struts) a Backing Bean(Ref JSF) or anything which stays at the Controller Layer)
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{
    /* There are few different implementations of getting   BeanFactory Resource
    In,the below example i have used XmlBeanFactory Object to create an instance of (Spring) BeanFactory */
    BeanFactory factory =
    new XmlBeanFactory(new FileInputStream("SpringResource.xml"));
    //write a Util Logic in your Implementation class using JFreeChart (or some open source chart library) and express the images by returning a  byte[]
    ChartService chartService =
    (GreetingService) factory.getBean("chartService");
    ViewBean vb = new ViewBean();
    vb.setPieChart(chartService.generatePieChart(request.getParameter("<someparam>"));
    vb.setBarChart(chartService.generateBarChart(request.getParameter("<someparam1>"));
    vb.set3DChart(chartService.generate3DChart(request.getParameter("<someparam2>"));
    chartService = null;
    HttpSession session = request.getSession(false);
    session.setAttribute("ViewBean",vb);
    response.sendRedirect("jsp/DisplayReports.jsp");
    }DisplayReports.jsp :
    ================
    <%@ page language="java" %>
    <html>
    <head>
    <title>reports</title>
    </head>
    <body>
    <h1 align="center">Pie Chart </h1>
    <center><img src="ImageServlet?req=1" /></center>
    <h1 align="center">Bar Chart </h1>
    <center><img src="ImageServlet?req=2" /></center>
    <h1 align="center">3D Chart</h1>
    <center><img src="ImageServlet?req=3" /></center>
    </body>
    </html>ImageServlet.java
    ==============
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
           byte buffer[];
            HttpSession session = request.getSession(false);
            ViewBean vb = (ViewBean) session.getAttribute("ViewBean");
            String req = request.getParameter("req");
            if(req.equals("1") == true)       
                buffer = vb.getPieChart();
            else if(req.equals("2") == true)
                 buffer = vb.getBarChart();
            else if(req.equals("3") == true)
                 buffer = vb.get3DChart();
            JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(new ByteArrayInputStream(buffer));
            BufferedImage image =decoder.decodeAsBufferedImage() ;
            response.setContentType("image/jpeg");
            // Send back image
            ServletOutputStream sos = response.getOutputStream();
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
            encoder.encode(image);
        }Note: Through ImageServlet is a Servlet i would categorise it under presentation layer rather to be a part of Controller and added to it all this could be easily relaced by a reporting(BI) server like JasperServer,Pentaho,Actuate................
    Hope the stated implementation had given some idea to you....
    However,If you want to further look into similar implementations take a look at
    http://www.swiftchart.com/exampleapp.htm#e5
    which i believe to be a wonderful tutor for such implementations...
    However, there are many simple (Open) solutions to the stated problem.. if you are Using MyFaces along with spring... i would recommend usage of JSF Chart Tag which is very simple to use all it requires need is to write a chart Object generating methos inside our backing bean.
    For further reference have a look at the below links
    http://www.jroller.com/page/cagataycivici?entry=acegi_jsf_components_hit_the
    http://jsf-comp.sourceforge.net/components/chartcreator/index.html
    NOTE:I've tried it personally using MyFaces it was working gr8 but i had a hardtime on deploying my appln on a Portal Server(Liferay).If you find a workaround i'd be glad to know about it.
    & there are many BI Open Source Server Appls that can take care of this work too.(Maintainace wud be a tough ask when we go for this)
    For, the design perspective had i've been ur PM i wud have choose BI Server if it was corporate web appln on which we work on.
    Hope this might be of some help :)
    REGARDS,
    RaHuL

  • Display byte array image or ole object in Section through dynamic code?

    To Start I am a Complete Newbe to Crystal Reports. I have taken over a project originally written in VS2003 asp.net using SQL Server 2005 and older version of Crytal Reports. I have moved project to VS2010 and Cryatal Reports 10 still using SQL Server 2005. Have multiple reports (14 to be exact) that display data currently being pulled from database suing a dataset, each report has from 4 to 14 Sections. I have modified database table with two new fields. Field1 contains string data with full path to a scanned document (pdf or jpeg). Field2 holds a byte array of the actual image of the scanned document. I have tested the database and it does infact contain the byte array and can display the image via VB.net code. I can make the report display the scanned image using ole object.
    Now my real question: I need to add a new Section and it should display either the byte array of the scanned image or the actual scanned image (pdf or jpeg) . How can I have it do either of these options via code dynamicly while application is running?

    First; only CRVS2010 is supported on VS2010. You can download CRVS2010 from here;
    SAP Crystal Reports, developer version for Microsoft Visual Studio: Updates & Runtime Downloads
    Developer Help files are here:
    Report Application Server .NET API Guide http://help.sap.com/businessobject/product_guides/sapCRVS2010/en/xi4_rassdk_net_api_en.zip
    Report Application Server .NET SDK Developer Guide http://help.sap.com/businessobject/product_guides/sapCRVS2010/en/xi4_rassdk_net_dg_en.zip
    SAP Crystal Reports .NET API Guide http://help.sap.com/businessobject/product_guides/sapCRVS2010/en/crnet_api_2010_en.zip
    SAP Crystal Reports .NET SDK Developer Guide http://help.sap.com/businessobject/product_guides/sapCRVS2010/en/crnet_dg_2010_en.zip
    To add the images, you have a number of options re. how to. You even have two SDKs that y ou can use (RAS and CR).
    Perhaps the best place to start is with KB [1296803 - How to add an image to a report using the Crystal Reports .NET InProc RAS SDK|http://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/oss_notes_boj/sdn_oss_boj_bi/sap(bD1lbiZjPTAwMQ==)/bc/bsp/spn/scn_bosap/notes%7B6163636573733d36393736354636443646363436353344333933393338323636393736354637333631373036453646373436353733354636453735364436323635373233443330333033303331333233393336333833303333%7D.do]. The KB describes how to add images to a report using the InProc RAS SDK, but also references other KBs that use CR SDK.
    Also, don't forget to use the search box in the top right corner of this web page.
    Ludek
    Follow us on Twitter http://twitter.com/SAPCRNetSup
    Got Enhancement ideas? Try the [SAP Idea Place|https://ideas.sap.com/community/products_and_solutions/crystalreports]

  • Package body greater than 2160 bytes does not compile in Object Browser

    Hi there,
    I initially created a package in Apex 2.1.0.0.39 using the Object Browser and it compiled OK. The message in the box above the source code says "PL/SQL code successfully compiled (17:51:08)". I then added more code and eventually when I clicked the "Compile" button" the message to say successfull compilation or any error message was not displayed. The box above the source code remains blank. After much trial and error I found that by adding just one more letter to the end of a comment that it would not compile, but by removing the letter then it would compile most of the time. I downloaded the package and found that the size of the download .PLB file was 2160 bytes. Editing the PLB file using a text editor to increase the size and executing it in SQL*PLUS does work.
    Is this a fundamental limit on the size of packages that can be compiled using the Object Browser, or is there an Apex configuration parameter that can be modified to allow larger packages? If this is a limit then why isn't an informational message displayed? Or is this in fact an installation issue or an issues with Apex Object Browser?
    Further information:
    Oracle Database 10g Express Edition Release 10.2.0.1.0 - Product
    PL/SQL Release 10.2.0.1.0 - Production
    CORE 10.2.0.1.0 Production
    TNS for 32-bit Windows: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - Production
    I installed this version back at the beginning of the year for training purposes and have not made any conifiguration changes that I am aware of, or installed any further upgrades/software since.
    All help gratefully received by this "definitely a nubie".
    Regards.
    John.

    John,
    If you are using, as you said, Application Express version 2.1.0.0.39, be aware that this is a very old (and not a supported) version. If you have trouble with the latest version (currently 3.2), feel free to report them here.
    Scott

  • Class Object into Byte Array

    Is there a way to copy a class object into a byte array? If so, how?

    hi check out
    http://forum.java.sun.com/thread.jspa?threadID=562268&
    messageID=2766098This does not work in j2me. WriteObject does not exist, and there are no serialsation interfaces in j2me. So you'll have to do that on your own.
    look here: http://java.sun.com/developer/J2METechTips/2002/tt0226.html

  • How do i convert an image object to a byte array ?

    Hi
    how do i convert an image object into a byte array
    early reply apperciated

    Oh sorry my method and the other method need to have the pixels from the Image passed to them which you get my using pixelgrabber:
    //create width and height variables from image
              int w = img.getWidth(this);
              int h = img.getHeight(this);
              //retrive picture from image
              int[] pix = new int[w * h];
              PixelGrabber pg = new PixelGrabber(img, 0, 0, w, h, pix, 0, w);
              try{ pg.grabPixels();
              } catch (InterruptedException ioe) {
                   System.err.println("Interrupted");
              if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
              System.err.println("image fetch aborted or errored");
              }

Maybe you are looking for

  • Hide data in a table view

    Hi, I need to hide data in a table..Only column headers required to display.. I tried by (display column headers only) in view..It is showing only column header in the view ..But when iam displaying the table in dashboard it displays data also..anoth

  • Is there a way to use multiple canvas tags with the ToolKit for CreateJS for Flash in one HTML5 doc?

    Hey everyone, I was wondering if someone could help point me in the right direction for solving this. I have created 5 short animations using Flash and when I published each ".fla " (with Toolkit for CreateJS extension) I get 5 different html5 files

  • SIM not provisioned on an ipad that has been operating for five years, help

    My ipad was installed at the same time as the MacBook Pro 5 years ago; I've never had to do anything with it other than upgrading the software (hook up to the MacBook Pro).  Now it shows "no service" and the network shows "sim not provisioned."  I wr

  • SQL for finding chunk or no keyboard values

    Hi all , I have table where users are allowed to enter data from excel sheet but while viewing it in application due to non key board values are like ¶,     ã, £ the validation getting failed and values are not loaded kindly help me in finding those

  • Error while running rtf

    Please help me where and how to identify the error in RTF. ConfFile: C:\Program Files\Oracle\BI Publisher\BI Publisher Desktop\Template Builder for Word\config\xdoconfig.xml Font Dir: C:\Program Files\Oracle\BI Publisher\BI Publisher Desktop\Template