How to test if object is a byte array?

hi,
does anyone know if there is a way for getting the Class constant for a byte[] that can be used with instanceof? like in below?
for the primitive boolean type there is Boolean.TYPE, which gives a Class object for a primtive type? but a boolean is not an object? I don't know if this is related to the above though??
thanks,
asjf
public class isByteArray
     public static void main(String [] arg) throws Exception {
          Object [] os = new Object [] { new byte [10],
               new java.awt.datatransfer.UnsupportedFlavorException(new java.awt.datatransfer.DataFlavor())
          for(int i=0; i<os.length; i++)
               System.out.println(os.getClass().getName()+" is byte [] ? "+isByteArray(os[i]));
     static byte [] b = new byte [0];
     public static boolean isByteArray(Object o) {
          return b.getClass().isInstance(o);
     /* would like */
     public static boolean isByteArray(Object o) {
          return o instanceof (byte[]).class;

thanks..
(I'd been trying
o instanceof (byte[])
and lots of other variations..)

Similar Messages

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

  • How to remove blank data from a byte array

    Hi All,
    How to remove blank data from a byte array. Suppose I created a byte array as byte[] b = new byte[8192] and i read the data as inputstream.read(b). If the data that has been received is only 1000 bytes length, how to find out how much data has been read or how to delete that blank 7192 bytes of data?
    Thanking you,
    Regards,
    Shankar.

    1) Always try to sidestep this by allocating only the necessary amount of space required...
    2) If 1 is not possible, you will have to index byte for byte how much data was read into the array which
    denotes reading byte for byte... not ideal as this is relatively slow...
    Are you reading from a file?

  • 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 to put a String into a byte array

    How can i put a String into a byte array byte[]. So that i can send it to the serial port for output to an LCD display. Cheers David

    javadocs for String
    getBytes
    public byte[] getBytes()
    Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
    Returns:
    The resultant byte arraySince:
    JDK1.1

  • How to save a value in a byte array, retrieve it and display it?

    Hi,
    I am doing a project for my data structures class that involves saving a value (given in String format) in a byte array (our 'memory'). Initially I just tried casting character by character into the byte array and casting back to char[] for retrieval (using .toString() to return what's supposed to be the original string), but this did not work. I tried the .getBytes() method, applying it to the string and then trying to recover it by placing the contents of the 'memory' in a byte array and applying toString(), but that didn't work either. I looked a bit and found this class, CharsetEncoder and CharsetDecoder. I tried to use these but when I try the compiler tells me I cannot instantiate CharsetDecoder because it is an abstract class. At this point I'm at a loss as to what I can do. Is there any way to place a string in a byte array and then recover the string in it's original format? For example, I might save a value in my particular class of "456". But when I try to recover the value from my 'memory' i.e. the byte array, it comes out like [gnue@hnju.... or something similar. I need it to output the original string ("456").
    Below is my code as it is right now, for the methods setValue and getValue.
    Thanks!
    public void setValue(String value) throws InvalidValueException {
         //… stores the given value in the memory area assigned to the variable
              if(this.type.isValidValue(value)){
                   bytes = value.getBytes();
                   int i,j,k;
                   int l=0;//might be wrong?
                   int ad=address-(address%4);
                   mem.readWord(ad);
                   reg=mem.getDataRegister();
                   if((address%4)+bytes.length-1<4){
                        for(i=address%4;i<address%4+bytes.length;i++)
                             reg.setByte(i, bytes[i]);
                        mem.setDataRegister(reg);
                        mem.writeWord(ad);
                   else if((address%4)+bytes.length-1>=4){
                        if(address%4!=0){
                             for(i=address%4;i<4;i++){
                                  reg.setByte(i, bytes);
                                  l++;
                             mem.setDataRegister(reg);
                             mem.writeWord(ad);
                             ad+=mem.WORDSIZE;
                        while(ad<address+bytes.length-(address+bytes.length)%4){
                             for(j=0;j<4;j++){
                                  reg.setByte(j, bytes[j+l]);
                                  l++;
                             mem.setDataRegister(reg);
                             mem.writeWord(ad);
                             ad+=mem.WORDSIZE;
                        if((address+bytes.length)%4!=0){
                             mem.readWord(ad);
                             reg=mem.getDataRegister();
                             for(k=0;k<(address+bytes.length)%4;k++){
                                  reg.setByte(k, bytes[k+l]);
                                  l++;
                             mem.setDataRegister(reg);
                             mem.writeWord(ad);
                   else
                        throw new InvalidValueException("The value passed is not valid.");
         /** Gets the current value of the variable.
         @return current value converted to String
         public String getValue() {
              //… returns the current value stored in the corresponding memory area
              //… value is converted to String
              bytes=new byte[this.getType().getSize()];
              int i,j,k;
              int l=0;//might be wrong?
              int ad=address-(address%4);
              mem.readWord(ad);
              reg=mem.getDataRegister();
              if((address%4)+bytes.length-1<4){
                   for(i=address%4;i<address%4+bytes.length;i++)
                        bytes[i] = reg.readByte(i);
              else if((address%4)+bytes.length-1>=4){
                   if(address%4!=0){
                        for(i=address%4;i<4;i++){
                             bytes[i] = reg.readByte(i);
                             l++;
                        ad+=mem.WORDSIZE;
                   mem.readWord(ad);
                   reg=mem.getDataRegister();
                   while(ad<address+bytes.length-(address+bytes.length)%4){
                        for(j=0;j<4;j++){
                             bytes[j+l] = reg.readByte(j);
                             l++;
                        ad+=mem.WORDSIZE;
                   if((address+bytes.length)%4!=0){
                        mem.readWord(ad);
                        reg=mem.getDataRegister();
                        for(k=0;k<(address+bytes.length)%4;k++){
                             bytes[k+l] = reg.readByte(k);
                             l++;
              return bytes.toString();

    You can certainly put it into a byte array and then construct a new String from that byte array. Just calling toString doesn't mean you'll automatically get a meaningful string out of it. Arrays do not override the toString method, so the use the one inherited from object.
    Look at String's constructors.

  • How to get the encoding of a byte array (or ByteBuffer)?

    Hello;
    I have a byte array which may be encoded with any kind of encoding and I want to determine which encoding was used to encode this byte array. Does anyone know how to do this?
    Thanks in advance..

    Byte Arrays have NO encoding at all. When bytes are packed to characters, that is where encoding comes into picture. java.lang.String has enough methods to do that.
    [email protected]

  • How to know the length of a Byte array?

    how to know the length a byte array if it is an argument of the method, e.g.
    public byte[] hash(byte[] data) throws Exception
    I wanna store the length of data into a integer in the method of hash, but no idea how to get it
    THanks!

    to conclude:
    I am a newbie, I wanna know , those "System"
    methods as well.What exactly does that have to do with your original question?
    or instance:
    System.arrowcopy() , where can I find the
    definition also?You probably meant System.arraycopy. The documentation is called JavaDoc and for Java 1.5 (a.k.a. 5.0) it can be found here: http://java.sun.com/j2se/1.5.0/docs/api/index.html
    If you've not yet found the API documentation, then I'm pretty sure you should start with some tutorials, they probably point to all the interesting documentation as well.

  • How to test Authority Object

    Hello freinds,
    I have inserted authority object in z program, how can I test the program whether the user is authorized to carry out the transaction or not???

    Hi Amar,
    Please place a brreak-point at the statement "AUTHORITY-CHECK" and execute the program.
    If you have authrization then sy-subrc will be set to zero else some different value.
    Regards,
    Babul.

  • How to test the object is base 64 encoded or not.

    Hi,
    MimeUtility is which I am using for base 64 encoding of object.
    but while decoding I want to test whether the object is base 64 encoded and then only I want to decode it. actually while encoding I will be encoding it based on some criteria. If that criteria is satisfied then I will be encoding the object else I will not do so but I cant test it same way again so I have to explicitly test whether its encoded at base 64 encoding then only decode it.
    Sorry it seems to a long story :)
    Thanks in advance.

    If that criteria is satisfied then I will be encoding the object else I will not do soSo, you're not saying what that criteria is, but you're asking if there is some way (and I suspect asking for some way) of determining, after the fact, whether that criteria was met.
    Depending on the criteria, and the method of encoding, I would have thought it quite possible for some object which was not encoded to be in every respect identical to the encoding of some other object. In this case it would not be possible to determine whether some arbitrary object was the result of an encoding.
    But then, as already pointed out, you know if you encoded something or not.

  • How to Read a File into a Byte Array??

    I want to make an array of data objects that works as a byffer to write from a file to another file
    do you have any sygestions?

    The way I would do it (if I dont misunderstand your question) is to use FileInputStream to pass in the streaming data source.
    then read the file source to a list object. For example, LikedList.
    then tell the LikedList to transcribe itself to an array of any type, in this case, byte.

  • How to convert an Image to a byte array?

    I want to make a screenshot and then convert the image to a byte of arrays so I can send it through a BufferedOutputStream.
    try
                   robot = new Robot();
                   screenshot = robot.createScreenCapture(new Rectangle(500,500));
                   imageFile = new File("image.png");
                   ImageInputStream iis = ImageIO.createImageInputStream(screenshot);
                   byte[] data = new byte[1024];
                   byte[] tmp = new byte[0];
                   byte[] myArrayImage = new byte[0];
                   int len = 0;
                   int total = 0;
                   while((len = iis.read(data)) != -1 ) // LINE 52 --- EXCEPTION CATCHED HERE
                        total += len;
                        tmp = myArrayImage;
                        myArrayImage = new byte[total];
                        System.arraycopy(tmp,0,myArrayImage,0,tmp.length);
                        System.arraycopy(data,0,myArrayImage,tmp.length,len);
                   ios.close();I get this exception while running:
    Exception in thread "Thread-0" java.lang.NullPointerException
    at Server.run(Server.java:52)
    at java.lang.Thread.run(Unknown Source)

    Fixed that. I got a new problem.
    When I connect to my simple server application that reads the image file, converts it to an array of bytes and sends it back, the file is created on the client side and it containts data, but I am not able to open the image. I have checked that the image that the server is sending is working. So where is the problem?
    The client application recieves the image as following:
    public void run()
            try
                socket = new Socket("127.0.0.1", 2000);
                BufferedOutputStream out_file = new BufferedOutputStream(new FileOutputStream("recieved_img.png"));
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                int inputLine;
                while((inputLine = in.read()) != -1)
                    char c = (char)inputLine;
                    System.out.println(c);
                    out_file.write(inputLine);
            catch(IOException err){ err.printStackTrace(); }
        }And the server sends the image like this;
    try
              socket = server.accept();
              in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
              out = new BufferedOutputStream(socket.getOutputStream());
              out.write(25);
              while((inputLine = in.readLine()) != null)
                   System.out.println(myArrayImage.length);
              System.out.println(inputLine);
                        out.write(myArrayImage);     // Send the array of bytes
         }

  • How to convert the record stored iin byte array to integers

    im making a simple game in j2me and i want to get the max scores and show it for each player , what i face right now that i cant convert the records which i stored in bytes to integers when i read it from file to get the max.
    thanks

    have a look at java.io.DataInputStream

  • How to convert  Wav file  in to byte array an vise vers into RMS???????????

    hi Constantinos Loizou
    i m having same problem which u were facing in last month.
    my problem i have to save .WAV file into RMS and then retreive it from RMS.
    my Code is
    Read From RMS
    RecordStore rsUser = RecordStore.openRecordStore(file,true);
    if(rsUser.getNumRecords() > 0)
    try {
    byte[] byusrinfo = rsUser.getRecord(1);
    InputStream in = new ByteArrayInputStream(byusrinfo,0,byusrinfo.length);
    p = Manager.createPlayer(in,"audio/x-wav");
    p.start();
    return true;
    catch(Exception ex) {
    ex.printStackTrace();
    return false;
    rsUser.closeRecordStore();
    catch(Exception ex) {
    ex.printStackTrace();
    return false;
    Write in RMS
    try {
    RecordStore rsUser = RecordStore.openRecordStore(file,true);
    int idata = is.available();
    byte[] exdata = new byte[idata];
    is.read(exdata);
    if(rsUser.getNumRecords() > 0) {
    rsUser.setRecord(1,exdata,0,exdata.length);
    else {
    rsUser.addRecord(exdata,0,exdata.length);
    rsUser.closeRecordStore();
    catch(Exception ex) {
    ex.printStackTrace ();
    now i have the file successfully when i retrieve it from RMS and p.reliaze() give me exception
    javax.microedition.media.MediaException: Failed to realize Player: Malformed wave media: expected 'RIFF'
    have u able to solve it. if yes then pls give me solution. or give other solution if this soution is not good
    regardz
    Hassan Mushtaq

    Well, I'm not going to give you your code on a silver platter. You'll need to put some effort in it yourself.
    So look at that available() method yourself an see if you can improve on that. Look at the api docs, there is loads of information there, and often it will give you pointers on why things are not working.

  • OpenScript: How do you test for object/text existance programmatically?

    Hi, All;
    I hope someone can help me; kind of new to OATS. I can’t figure out how to test for object/text existence and return results back to the script. There are methods for verifying text and objects; i.e.
    Web.verifyText
    Web.assertText
    These methods just report pass or fail to the test. I need to get the data back programmatically so I can use it logically. I know you can do this pretty easily in Selenium and QTP so there must be a way in OATS.
    Thanks,
    Eric

    Hi Eric,
    You can use the Object Explorer to find the xpath of the object you are interested and check for its existence, and then grab some attribute of that object for use elsewhere.
    if (web.element(6,"/web:window[@index='0' or @title='Software and Services - SCL']/web:document[@index='0']/web:span[@text='Services' or @index='14']")
                             .exists()){
              System.out.println("OBJECT EXISTS");
    // get an attribute of object here ,e.g
    String myval = web.element(41,"/web:window[@index='0' or @title='Software and Services - SCL']/web:document[@index='0']/web::span[@text='Services' or @index='14'].getAttribute("innerText");
    // use myval elsewhere
    Hope it helps.
    Jamie

Maybe you are looking for

  • HT1689 how can i get a list of purchases, like for in app purchases?

    i have had issues with an app, and was asked to submit receipts for what I had bought. My app crashed with an update and beeline said they would credit my account if I had receipts. I did not save every receipt apple gave to me. Is there a way to vei

  • KEYBOARD AND MOUSE

    Lately my keyboard and mouse just stop working, the keyboard misses typed letters, mouse doenst move, and if I just unplug and plug again the wireless stick it works again, plus I listen from time to time the windows sound of when you reconnect a usb

  • YouTube and "Matched third party content".

    I have known for a few years that YouTube employs software that can detect videos containing audio from commercial CDs etc. but I didn't know how incredibly efficient it is. I filmed a large theatrical event ten days ago and yesterday uploaded almost

  • What does a new non-DE user need? | Help for a Wiki page

    Hey Archers, I'm using Arch with the Compiz Standalone Window Manager and I need some help for a project. It turns out (who knew) that computers need a lot more to run smoothly than just a desktop and applications. You need network managers, gtk them

  • Taking the Components into Production process

    Hi All, I have got one Businee Scenario for i need to map in SAP. Scenario: Customer is sending the Components for making the finished goods. In this case Business will be using the customeru2019s components for production process. Now, How to take t