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

Similar Messages

  • 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 to convert bytes[] into File object

    hi
    how to convert byte array into File object
    pls.. help me
    Regards
    srinu

    rrrr007 wrote:
    Hi,
    How to convert bytes[] into multipage File object?? ]There's no such thing as a "multipage File object." You ought to re-read this thread closely, and read the [API docs for File|http://java.sun.com/javase/6/docs/api/java/io/File.html] to clear up your confusion about what a File object is.
    I used the java.io.SequenceInputStream to concatenate two input streams (basically .pdf files) into a single input stream. I need to create a single multipage pdf file using this input stream. Then you need a pdf API, like iText or fop. You can't just concatenate pdf files, word docs, excel sheets, etc., like you can text files. Google for java pdf api.

  • How to convert bytes[] into multipage File object

    Hi,
    How to convert bytes[] into multipage File object??
    I used the java.io.SequenceInputStream to concatenate two input streams (basically .pdf files) into a single input stream. I need to create a single multipage pdf file using this input stream.
    Thanks for you help in advance..

    Only text format allows you to concatenate two files together to get a longer files.
    Most formats have a header and a footer and so you cannot simply add one to the other.
    You need to use a PDF API which will allow you to build the new document (if one exists)

  • How to read a binaryfile into an object

    Hello,
    I want to read a binary file into an object. In this object, we have
    several variables which need to be filled. I did the following thing:
    ---Start code---
    import java.io.*;
    import java.lang.reflect.*;
    public class BinaryFile {
      private File file;
      private DataInputStream dis;
      public BinaryFile() {}
      // Open the file
    public void openFile(String file) throws FileNotFoundException {
        this.file = new File(file);
        if (! this.file.exists())
          throw new FileNotFoundException();
        dis = new DataInputStream(new FileInputStream(this.file));
      // Close the file
      public void closeFile() throws IOException {
        dis.close();
    public void readObject(int offset, Object o) throws EndOfFileException,
                           IOException {
        // Get the fields in the object
        Field[] fields = o.getClass().getFields();
        try {
          String type, naam;
          Class className;
          int lengte, arrayLengte;
          boolean isArray;
          for (int i = 0; i !< fields.length; i++) {
            naam = fields.getName(); // Get the name of the field
    className = fields[i].getType(); // Get the type
    type = className.getName(); // Get the name of the type
    isArray = className.isArray(); // Is it an array?
    arrayLengte = 1;
    fields[i].setAccessible(true); // For setting the values
    if (isArray) {                      // If it is an array,
    type = getType(type); // decode it
    // Get the size of the array
    arrayLengte = Array.getLength(fields[i].get(o));
    // Determine the type of the variable and fill it.
    // Char
    if (type.equalsIgnoreCase("char")) {
    lengte = 1;
    if (isArray)
    fields[i].set(o, readChars(arrayLengte * lengte));
    else
    fields[i].setChar(o, readChar());
    // Byte
    } else if (type.equalsIgnoreCase("byte")) {
    lengte = 1;
    if (isArray)
    fields[i].set(o, readBytes(arrayLengte * lengte));
    else
    fields[i].setByte(o, readByte());
    // Short
    } else if (type.equalsIgnoreCase("short")) {
    lengte = 2;
    if (isArray)
    fields[i].set(o, readShorts(arrayLengte * lengte));
    else
    fields[i].setShort(o, readShort());
    // Int
    } else if (type.equalsIgnoreCase("int")) {
    lengte = 4;
    if (isArray)
    fields[i].set(o, readInts(arrayLengte * lengte));
    else
    fields[i].setInt(o, readInt());
    // Float
    } else if (type.equalsIgnoreCase("float")) {
    lengte = 4;
    if (isArray)
    fields[i].set(o, readFloats(arrayLengte * lengte));
    else
    fields[i].setFloat(o, readFloat());
    // Long
    } else if (type.equalsIgnoreCase("long")) {
    lengte = 8;
    if (isArray)
    fields[i].set(o, readLongs(arrayLengte * lengte));
    else
    fields[i].setLong(o, readLong());
    // Double
    } else if (type.equalsIgnoreCase("double")) {
    lengte = 8;
    if (isArray)
    fields[i].set(o, readDoubles(arrayLengte * lengte));
    else
    fields[i].setDouble(o, readDouble());
    catch (IOException ioex) {
    throw ioex;
    catch (Exception ex) {
    ex.printStackTrace();
    // Methods for reading from the DataInputStream
    private char[] readChars(int lengte) throws IOException {
    char[] c = new char[lengte];
    for (int i = 0; i < c.length; i++)
    c[i] = dis.readChar();
    return c;
    private char readChar() throws IOException {
    return dis.readChar();
    private byte[] readBytes(int lengte) throws IOException {
    byte[] b = new byte[lengte];
    for (int i = 0; i < b.length; i++)
    b[i] = dis.readByte();
    return b;
    private byte readByte() throws IOException {
    return dis.readByte();
    private short[] readShorts(int lengte) throws IOException {
    short[] s = new short[lengte];
    for (int i = 0; i < s.length; i++)
    s[i] = dis.readShort();
    return s;
    private short readShort() throws IOException {
    return dis.readShort();
    private int[] readInts(int lengte) throws IOException {
    int[] i = new int[lengte];
    for (int j = 0; j < i.length; j++)
    i[j] = dis.readInt();
    return i;
    private int readInt() throws IOException {
    return dis.readInt();
    private double[] readDoubles(int lengte) throws IOException {
    double[] d = new double[lengte];
    for (int i = 0; i < d.length; i++)
    d[i] = dis.readDouble();
    return d;
    private double readDouble() throws IOException {
    return dis.readDouble();
    private float[] readFloats(int lengte) throws IOException {
    float[] f = new float[lengte];
    for (int i = 0; i < f.length; i++)
    f[i] = dis.readFloat();
    return f;
    private float readFloat() throws IOException {
    return dis.readFloat();
    private long[] readLongs(int lengte) throws IOException {
    long[] l = new long[lengte];
    for (int i = 0; i < l.length; i++)
    l[i] = dis.readLong();
    return l;
    private long readLong() throws IOException {
    return dis.readLong();
    // If it is an array, decode it. The type will be "[x" where x is
      // translated according to the table
      private String getType(String type) {
              BaseType Character  Type  Interpretation
              B  byte  signed byte
              C  char  Unicode character
              D  double  double-precision floating-point value
              F  float  single-precision floating-point value
              I  int  integer
              J  long  long integer
              L<classname>;  reference  an instance of class <classname>
              S  short  signed short
              Z  boolean  true or false
              [  reference  one array dimension
        int arrayIndex = type.indexOf("[");
        if (arrayIndex != type.lastIndexOf("[")) {
          System.out.println("Multiple arrays not supported!");
          return type;
    char tempType = type.charAt(arrayIndex + 1);
    switch (tempType) {
    case 'B':
    type = "byte";
    break;
    case 'C':
    type = "char";
    break;
    case 'D':
    type = "double";
    break;
    case 'F':
    type = "float";
    break;
    case 'I':
    type = "int";
    break;
    case 'J':
    type = "long";
    break;
    case 'S':
    type = "short";
    break;
    default:
    System.out.println("Couldn't define this type: " + type);
    type = type;
    break;
    return type;
    ---End code---
    Now the problem. I want to read the header of an executable. I turn to
    the file format as described in WINNT.H. If it is a char, it will read
    ok. For everything else, it doesn't work. A WORD (= short in java) for
    instance, doesn't come up with the real value.
    The purpose of this piece of code is to emulate the structs that are
    used in C.
    What is the problem here and what is the solution?

    before coding a long class, look at Serialization mechanism in java
    maybe (or maybe not) it should be a better soution ...

  • Conver bytes into UIImage

    Hello all,
    I get image data in bytes(0xFFD8....) from Sql Server 2005.
    Now i want to convert that data into UIImage.
    For that i first convert that bytes into NSData then NSData into UIImage.
    But i get null in UIImage.
    Thank you..

    BalusC wrote:
    stevoo wrote:
    Basicly this is what i want to do:
    Convert an image into a byte[]I would rather use an InputStream.Why ? is there any sort of difference ?
    >
    byte[] buffer = new byte[4096];
    // response.addHeader("", "");
    DataInputStream in = new DataInputStream(new FileInputStream("/home/stevoo/Desktop/Net/a.jpg"));
    in.readFully(buffer);
    in.close();i can do it with this, but i am not sure this is the best way.Bad code. DataInputStream is not needed here. Also if that image was larger than 4096 bytes, then your code is simply ignoring the remaining bytes.Yes it is very bad. I have changed everything. This was mostly trial.
    Using ejb, creating an object and persisting the picture in the database. this is working correctly i think.Huh? You thinks? Don't do that. Be sure.
    Well offcourse i think. I can put input stuff into the db but i am not sure if they are correct since i cant retrieve them to see if they were entered correctly.
    and My trouble is retrieving the image.
    I can retrieve them using a simple query, but how will i manage to turn then into an image again and display it?
    I am working with JSP and EJB.Write a servlet which takes the image ID as parameter, gets the stream from the database (by EJB, if need be) and writes it to the outputstream of the response along the correct response headers. Then call that servlet with the image ID as parameter in a HTML <img> element in JSP.
    I have already began work on the servlet. If i have more problem on this one
    In the future, please post Servlet related questions in the Servlet forum.i will post a new thread in the servlet section.
    Thanx :)

  • What is the efficient way of insert some bytes into a file?

    Hello, everyone:
    If I want to insert some bytes into a file (for example, insert the bytes before all the original content of the file, or append the bytes to a file), and the size of the original file is very big. I am wondering what is the efficient way? Where can I get some sample codes?
    regards,
    George

    Thanks, DrClap.
    I have tried your method and you are correct. I have written a simple program which can be used to insert "Hello World " to the start of a file ("c:\\temp\\input.txt"), and I have verified that it can work. Please help to see whether it is correct and whether it has a more efficient way.
    public class TestDriver {
         public static void main(String[] args) {
              byte[] back_buffer = new byte [1024];
              byte[] write_buffer = new byte [1024];
              System.arraycopy("Hello World".getBytes(), 0, write_buffer, 0, "Hello World".getBytes().length);
              int write_buffer_length = "Hello World ".getBytes().length;
              int count = 0;
              FileInputStream fis = null;
              FileOutputStream fos = null;          
              try {
                   fis = new FileInputStream (new File("c:\\temp\\input.txt"));
                   fos = new FileOutputStream (new File("c:\\temp\\output.txt"));
                   while ((count = fis.read (back_buffer)) >= 0)
                        fos.write(write_buffer, 0, write_buffer_length);
                        System.arraycopy (back_buffer, 0, write_buffer, 0, count);
                        write_buffer_length = count;
                   //write the last block
                   fos.write(write_buffer, 0, write_buffer_length);
                   fis.close();
                   fos.close();
                   //copy content back into original file
                   fis = new FileInputStream (new File("c:\\temp\\output.txt"));
                   fos = new FileOutputStream (new File("c:\\temp\\input.txt"));
                   while ((count = fis.read (back_buffer)) >= 0)
                        fos.write(back_buffer, 0, count);
                   fis.close();
                   fos.close();
                   //remove temporary file
                   File f = new File ("c:\\temp\\output.txt");
                   f.delete();
              } catch (FileNotFoundException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   try {
                        fis.close();
                   } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                   try {
                        fos.close();
                   } catch (IOException e2) {
                        // TODO Auto-generated catch block
                        e2.printStackTrace();
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   try {
                        fis.close();
                   } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                   try {
                        fos.close();
                   } catch (IOException e2) {
                        // TODO Auto-generated catch block
                        e2.printStackTrace();
    }regards,
    George

  • How to populate data into view object

    Hi all,
    I am quite new with ViewObject.
    I have one data table which is binding with view object.
    I want to populate data into view object from my managed bean.
    how can i achieve this kind of scenario?
    actually i try to get view object as in the following. but i get only null.
    ViewObject viewobject = DCIteratorBinding.getViewObject();
    With Regards,
    Wai Phyo

    Hi,
    You could use the following code snippet to get handle to view object from the iterator.
    FacesContext fc = FacesContext.getCurrentInstance();
    BindingContainer bindings =
    (BindingContainer)fc.getApplication().evaluateExpressionGet(fc,
    "#{bindings}",
    BindingContainer.class);
    DCBindingContainer bc = (DCBindingContainer)bindings;
    DCIteratorBinding iterator =
    bc.findIteratorBinding("<ITERATOR_ID>");
    ViewObject viewObject = iterator.getViewObject();
         // Perform operations on the view objectThanks,
    Navaneeth

  • How do I copy text and objects from pages to and paste into Email, objects don't show in Email

    Anyone know how I copy text and objects from pages and paste into Email, objects don't show in Email, thanks

    You can't expect Mail to support all the objects of Pages which can include anything up to charts generated from spreadsheet tables.
    Even if Mail was a superset of Pages, what would the recipients who don't have either Mail or Pages, make of it?
    Peter

  • Loading swf into movieclip object

    I am trying to load a swf file into a movieclip object on the
    stage. The movieclip object is sized smaller than the screen, and
    placed in the middle. I have defined a loader with:
    var myMovieClipLoader:MovieClipLoader = new
    MovieClipLoader();
    then use it like this:
    _level0.myMovieClipLoader.loadClip("moviename.swf",
    _level5.movieclipinstancename);
    (the movieclip object is used in a swf loaded in level5)
    When I load the swf like this, the swf loads at the correct
    location according to where I have placed the movieclip object,
    however it "blows up" to fill the screen from that point down and
    across, ignoring the size of the movie clip object (the loading swf
    actually expands beyond it's created size to fill the screen,
    making all the graphics and text much larger than intended). The
    actual pixel size of the swf I'm trying to load matches the size of
    the movieclip object (1024x350 in a 1280x1024 screen).
    What is the magic setting or property that will tell the
    loading swf to honor the size of the movieclip object I'm loading
    into?
    Thanks for your help!
    Barb

    Something I've been working on:
    Place the following code in a new file <your project
    folder>\as\MovieContainer.as
    Then open the properties for the symbol you want to be your
    movie container
    Set the AS 2.0 Class to as.MovieContainer and give it a name
    (I named mine 'loader').
    To load the movie, simply call:
    loader.queueSWF('my.swf');
    Hope that makes sense. Basically, it's just a self contained
    class for loading into an object on the scene. It draws a simple
    progress bar on the center of the symbol when it's loading and it
    resizes the loaded object on init to conform to the size of the
    object on the stage. Why queueSWF? Well, if it's currently loading
    a SWF, it will wait till it's finished and load a new one. The
    biggest problem right now is the progress bar, but it's fairly easy
    to remove if you don't like it. Hopefully it helps.
    If anyone else is reading this. I'm trying to figure out if I
    can load these movies into an array of movieclips. So far I've had
    no luck. If you know of a way, feel free to drop some input.

  • Size (in bytes) of an object? How to find?

    Hello, in C++ there is a "sizeof()" function that determines the number of bytes a particular data type has.
    My question is this: is there a similar function in java to determine the number of bytes of an "object" that i created?
    ie........ sizeof(MyCarObject)

    The size of an object in memory? Sorry, there's no way you can do that... You can try serializing the object to a file and using the size of that file as a measure but that isn't accurate.
    Why would you want to do it anyway?

  • How to cram two bytes into a short?

    Hi all,
    I have some byte[] data that I am receiving, and I need to put two bytes into one short (or int, or whatever), as the byte[] will form a two bytes-per-pixel image. I've been working with 8-bit data (this is 12-bits, NOT packed), which is much easier to manipulate.
    I currently have this method to convert a byte[] of 8-bit data into a short (I do this because Java does not support signed types and I need that 8th bit):
    private short[] convertBytesToShorts(byte[] data) {
         short[] convertedData = new short[data.length];
         for (int i = 0; i < data.length; i++) {
              convertedData[i] = (short)((short)data[i] & 0xff);
         return convertedData;
    }Is there a way to modify this to place two bytes into one short? Is it possible to just AND two bytes with 0xff and add them together to create one short? Surely it cannot be that simple. Also, remember that I must treat the values as unsigned.
    Furthermore, the two bytes look like this:
    | xxxx xxxx | xxxx 0000 |So the last four bits in the second byte are 0s.
    Any advice is appreciated.
    Message was edited by:
    Djaunl

    I've been working with 8-bit
    data (this is 12-bits, NOT packed), Obviously that is contradictory.
    I currently have this method to convert a byte[] of
    8-bit data into a short (I do this because Java does
    not support signed types and I need that 8th bit):
    Yes it does. The fact that it displays a byte as and integer and the conversion in that process produces a negative display value has nothing at all to do with the bits.
    Is there a way to modify this to place two bytes into
    one short? short s = (short)(((b1 << 8) & 0x0ff) | (b2 & 0x0ff))
    Of course you still have to deal with getting the order correct.
    (You can probably get rid of that first mask but you would need to test that.)

  • How to convert a string into an objects name?

    Hi
    I have the following problem;
    I have a string
    String a = "e1"
    and a method
    call(Event e1) that calls the "Event" class with object the name of the string a.
    How can I convert the strings name into an object so as to use it in the "call" method?
    Any ideas?
    Thanks in advance

    I don't know if this helps you, but you can do things like this.
    String a = "com.example.SomeEvent";
    //Instantiate com.example.SomeEvent
    Object o = Class.forName(a).newInstance();SomeEvent must have a non-argument constructor for this to work.
    Class that will be instantiated depens on runtime value of String a, and can be different across different executions of the program.

  • How to extract Cognos Data into Business Objects?

    Hi All,
    I would like to know whether anyway to pull Cognos data into Business Objects?
    1. Pull data thru Universe from Cognos Cubes?
    2. Pull data using Crystal reports from Cognos Cubes?
    3. Or any otehr method of pulling data from Cognos Cubes?
    If nothing is possible I would have to explore using the RDBMS Tables to build Universe, WebI and then present in Xcelsius. Anybody is aware of getting data from Cognos?
    Thanks in advance.
    Alex.

    Cognos Reporting on SAP BI data
    We need to create a new project to import the structure of the SAP BI cube or Multiprovider.
    Enter User ID and password.
    Click on OK
    It will ask you to enter the User ID and password again. After enter the User ID and password it will ask you to select the language.
    Then it will ask you to select the metadata source, select the Data source as shown in below fig. and click next.
    Select the data Source as shown in below.
    Here we are planning to import SAP BW cube so we have to select SAP BW and click on next.
    Select sign on and Click on OK.
    Here we have to select our desired cube or multiprovider and click next.
    Now we have to select the language again.
    Here Cognos is giving the flexibility to use different options when importing cube structures.
    Here I am selecting to use the technical name of the objects and to bring same model as it is in SAP BI.
    Finally it will show list of all objects which are imported from SAP BI.
    When you click on finish it will take to the frame work manager. There you will see the SAP BI Cube Structure.
    Now it is exactly imported like SAP BW extended star schema model.
    Here you can compare the technical names of the dimensions in both in Cognos and SAP BI is same.
             COGNOS    Model                                         SAP BI Cube model         
    Here I am comparing the values of the info Objects with in one dimension.
                   Cognos Model                                                   SAP BI Model
    If there are any hierarchies in BI, it will form separately as shown in below fig.
    When you open the main object of Program definition, we will find 3 objects under this.
    It is always recommendable to use Level 01 objects.
    This is how it looks when you open all the above 3 objects. You can use any of those depends on your report requirement.
    When you open the info object if you see number of different items, that means this info object has got attributes in it.
    0COMP_CODE is the technical name of the info object in BI.
    In Cognos if it technical name starts with 1  Short Text of the Info Object.
                                                                       2  Key of the Info Object.
                                                                       4  Long Text of the Info Object.
                                                             5  Medium Text of the Info Object.
    LELEL00  Is Summarized values.
    LEVEL01  Is Item level values of Info Object.
    Once you see this in bw/bi environment, i hope you know how to gather and use it in BOBJ environment !!

  • Convert MBox into XML into Java Objects

    Hello all,
    this is a general question, i dont know weather there is such libs or not.
    However, please tell me what you know.
    i want to program a java application for searching purpose in Mbox.
    i thought its possible and easier to try to convert the emails from the MBox into XML files, and from these create java objects when i need or even convert the XML into html for viewing.
    Any suggestions are welcome.
    Also antoher solutions are greate.
    thanks in advance!
    Sako.

    I don't know what this MBox you speak of is - I assume it's not the thing I use to hook upa guitar to GarageBand. Maybe you mean it as a generic term for mailbox? The easiest solution (to my mind) would be to use a Java API provided by whatever MBox is. If there is no such thing, then if you get XML-formatted version of the messages I suppose writing code to parse the XML into Java Objects would be a good option if you wanted to do further manipulation of them, but if all you want to do is display them as HTML in a browser then just use XSLT to transform them.
    Good Luck
    Lee

Maybe you are looking for

  • Can we view data in Multiprovider

    Hello All In one of my interview he asked me can v view data in multiprovider.(Not in reporting level). I said no,he said yes? If anyone knows abt this pl let me know. Regards balaji

  • Portege M100 with PM 1,2 processors, but only run on 598MHz

    Please help, I have 10 pcs M100, and 7 of them have no setting in Bios for "CPU Dynamic Frequencies Setting" (set the CPU speed, always low, always high, dynamic). The notebook that don't have that setting always run at 598 MHz. I already check with

  • File sharing only works for users with Admin rights

    Hi. I am trying to set up file sharing in Lion Server but am having problems getting all my users access to shared folders. So far, only users that are "allowed to administer this server" are seeing shared files, even though they seem to have "read/w

  • TTG HTML Gallery

    TTG HTML Gallery is pretty much what it sounds like: a new HTML gallery for Lightroom. It outputs valid XHTML and CSS, and a lot more customization options than the LR HTML gallery. It boasts thumbnail annotations, ratings, color labels and onImage N

  • Combine Year and Month two Dimensions together side-effect

    My user ask me to combine Year and Month(Period) those two dimensions as one dimension. I found it will be difficult to get TB-Last amount except "Hard Code" For example: I got three years :2007,2008, 2009 One Banance Account: Current Asset 12 Months