Constructing JarInputStream from byte[]

i want to use a 2 step process for accessing the contents of jar files.
first, i create the jar file from the shell:
$ jar cfv /tmp/x.jar *class
i inspected the exact size of the file from the shell:
*$ ls -l /tmp/x.jar*
_(step #1):_
i read a jar file from the file system into a byte[] and store it as an instance variable.
_(step #2):_
at a later time, sometimes i read classes from this byte[] .
so, this is my code:
if(jarFileImage.length == RealFileLength) { System.out.println("exact same size as in file system."); } // ok
JarInputInputStream jin = new JarInputStream(new ByteArrayInputStream((byte[]) jarFileImage)); // ok
if(jin.available() == 1) { System.out.println("so far so good"); } // ok
JarEntry je = jin.getNextJarEntry(); // <--- error "null pointer exception"
// this also fails :
Manifest mani = jin.getManifest();   // <--- error "null pointer exception"Streams are so basic and straight forward, i can't see what to inspect further.
Edited by: kappa9h on Feb 19, 2008 7:10 AM

i have made good progress and am way past the null-pointer exception.
What is this? An extra Input in there?i think that the root cause is really a networking issue. specifically,
i am serializing objects into the payload of DatagramPackets and multicasting them with udp .
to guarantee remote de-serialization, i include the relevant jar file in the same datagram.
JarInputInputStream jin = new JarInputStream(new ByteArrayInputStream((byte[]) jarFileImage));here, *((byte[]) jarFileImage)* is the jar file. the other part of the payload is the serialized object.
the two problems are:
(1) my understanding is that you can't read/write primitives like bytes/ints/doubles/etc. on the same Stream that you serialize objects.
for example:
objOutStream.writeObject(myObj);
objOutStream.writeObject((List<Byte>) jarImageAsObj); // okverse:
objOutStream.writeObject(myObj);
objOutStream.write((byte[]) jarImage);  // error(2) there is a maximum size of a DatagramPacket .
notice also that treating byte[] as a collection of Byte objects confounds the max. packet size. issue.
i did solve issue #1. i could not solve issue #2.
i think:
max DatagramPacket size is 64-k? more than anything i hope to expand this.
but there is also an issue of DatagramSocket buffer sizes. there are so many
moving parts such that i don't really understand.
for small jar files, everything works ok.
but when i use relatively large jar files, i get this:
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2279)
at java.io.ObjectInputStream$BlockDataInputStream.readInt(ObjectInputStream.java:2272)
which hints to me that, indeed, the limited size of the DatagramPacket payload truncates the jar file.
i don't have a clear view of whats really going on here. i am mostly beginner.
if anyone has an ideas, i will do more testing.
otherwise, i give-up and use my tcp based class loader.
but this breaks the encapsulation that i want.
thanks for reading so much.
Edited by: kappa9h on Feb 20, 2008 3:32 AM

Similar Messages

  • JavaMail Attachment from byte[]

    Hey!
    For my internship I have implemented a Jilter for a Sendmail Mailserver. In this Jilter I have to save messages and there it is only possible to get the body of an e-mail in form on a ByteBuffer.
    And for the fact that I have to store some e-mail messages I only save the body as byte[] into my database.
    In some cases I have to use these messages again in my online application. Here I build a new e-mail with the existing sources from database.(Subject, Body, Recipient, Sender,...). I build these new messages with JavaMail and then send them. (This whole project is kind of a filter, where you can specifiy who is allowed to send you messages and who's not. And it should be possible to unblock messages afterwards so that you will receive them, altough they've been blocked)
    My whole Application works fine if there's only text in the e-mail that should be unblocked. If there are some attachments (except from *.txt) I've the problem that the attachments are represented in textform.
    So how can I manage to construct a new Message with JavaMail from my existing sources (the body as a byte[]) where everything works fine with the attachments and where they are displayed normally (in files)? Is it even possible to construct this from only a byte[]?
    I've read some Javadoc i.e. Mime MultiPart stuff etc but there I've to add the files one after another.... But I only have my byte[]. And the only thing I'm able to save from the Jilter is the Content-Type. So I know if I've attachments in my message or not, but I don't know how much attachments and what type of.
    Has anybody an idea to solve this problem?
    Kind regards,
    Sandra

    Thanks for your reply.
    I tried to construct the MimeMessage with the SharedByteArrayInputStream but I didn't succeed. I also got back in my e-mail a long text with the encoded bytes but no files.
    SharedByteArrayInputStream body_bytes = new SharedByteArrayInputStream(my_saved_message.getBody());
    MimeMessage msg = new MimeMessage(session, body_bytes);
    Now I tried to construct a MimeBodyPart but it also doesn't work.
    SharedByteArrayInputStream body_bytes = new SharedByteArrayInputStream(message.getBody());     
         MimeMessage msg = new MimeMessage(session);
         Multipart mp = new MimeMultipart("mixed");
         BodyPart bodyPart = new MimeBodyPart(body_bytes);
    mp.addBodyPart(bodyPart);
    BodyPart bodyText = new MimeBodyPart();
    bodyText.setText(" " + body_prefix + " " + message.getSender() +
                   "\n" +
                   "--------------------------------------------------------------" +
                   "\n"
                   + "--------------------------------------------------------------" +
                   "\n \n \n \n ");
    mp.addBodyPart(bodyText);
    msg.setContent(mp);     
         msg.addRecipients(Message.RecipientType.TO, message.getRecipient());
         msg.addFrom(addresses);
         msg.setSubject(subject_prefix + " " + message.getSubject());
         Transport.send(msg);
    I only have the body as a byte[] and not the whole RFC message. I also want to add some text to the message.
    Do you have any idea what other solution might exist?

  • NLS_LENGTH_SEMENTICS from BYTE TO CHAR

    Hi,
    For supporting multibyte character, we need to change NLS_LENGTH_SEMENTICS parameter from BYTE to CHAR. But this parameter setting will effect for new database tables created thereafter. To change the storage characteristics for existing database tables we explicitly executed Alter statements for database tables for columns having datatype as “Varchar2” and “Char”.
    Problem:
    ======
    Since the number of database tables in PRODUCTION are very high and contains approx. 600 million of records spread over 400 database tables, we are not in a position to afford the time which will be spent in altering these database tables in PRODUCTION.
    We ran the test by alter script in System Test environment and alteration of database tables covering 150 tables and 200 million of records was carried out in almost 16-20 hrs.
    APPROACHES WE HAVE IN MIND
    ==========================
    1. Alter all the table columns (We tried the same and taking too much time)
    2. Export /Import with NLS_LENGTH_SEMENTICS set as CHAR(We discuss with our DBA about this approach and found that it will also take too much time and there is RISK of data inconsistency)
    3. Drop the index of the table, run alter script for changing storage type BYTE to CHAR , and rebuild the index (this is also taking too much time).
    All above approaches are very costly in terms of time, that we cannot afford.
    If any one having better solution then please suggest.
    thanks in advance
    Syed

    Hi
    We are also facing a similar problem
    We ran alter table scripts and now compiling the objects
    and that is taking lot of time.
    we have around 4000 invalids that by parallel recomp came down to 2000 but still these 2000 which are mostly packages .. are giving a hard time.
    if anyone has faced/found a similar issue/solution pls post. or maildirectly to me.
    Sunil Choudhary

  • Coversion from byte stream to character & character to byte stream.

    This is a test program.
    import java.io.*;
    class Test
         public static void main(String[] args)
              System.out.println("Hello World!");
              try
                   BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:/javafiles/testing/Picture.jpg"))));
                   PrintWriter bw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File("C:/javafiles/testing/Copy.jpg"))));
                   String in = br.readLine();
                   while (in != null)
                        bw.println(in);
                        in = br.readLine();
                   br.close();
                   bw.close();
              catch (Exception e)
                   System.out.println("\n\n**********Exception Occured**************\n" + e);
    **First of all I read jpg file convert it into character stream from byte stream.
    **and copy it back and convert it back into byte steam from character stream.
    **The file copied back is corrupted.(getting open but display has fully scattered.)
    **That means data has been lost in conversion.
    **is it due to the encoding, I havn't specified while writing, or it always happens when we convert from byte stream to character and vice versa.
    **What encoding should I use while writing jpg files.
    please comment.

    **First of all I read jpg file convert it into
    character stream from byte stream.
    **and copy it back and convert it back into byte
    steam from character stream.First of all this operation is meaningless. A JPEG file doesn't contain anything that can be converted to characters. Delete the 'conversions' and all will be well.
    **What encoding should I use while writing jpg files.None. Don't use an encoding. Don't use Readers and Writers. Use InputStreams and OutputStreams only.

  • How to construct polygons from triangles for animations?

    Since there is no way of filling polygons in other devices than those that use the NokiaUI,I need to construct polygons from triangles. Can someone give me a good example of an algorithm for this?
    My product contains 10 hypnotic screensavers. New polygons are constructed from mathematical calculations for each frame in the animations. Would it be possible to construct these polygons from triangles in an automatic
    way and would that be fast enough? You can find more information about my product on my site:
    http://www.mobile-visuals.com/mobilesoftware.php
    The version for Nokia and SE available to download for free on Joiku:
    http://www.joiku.com/?action=products&mode=productDetails&product_id=252
    I want to release it for Motorola and Samsung too.

    One thread for one topic is enough. All responses may please be posted on
    {color:0000ff}http://forum.java.sun.com/thread.jspa?threadID=5243181{color}
    db

  • Can not construct xml from relative xpath expression: //FormVar

    In version 7.0, it was possible to access Form Variables with the (valid) XPath Expression "//FormVariable".
    In 7.2.2, using this XPath Expression leads to a stalled action, with message: "can not construct xml from relative xpath expression: //FormVar". (see full stack trace below)
    What's wrong? How can I fix this?
    Use of relative expression is very very useful during the development phase!
    Best Regards,
    com.adobe.workflow.WorkflowRuntimeException: can not construct xml from relative xpath expression: //FormVar
    at com.adobe.workflow.pat.service.PATExecutionContextImpl.createNodesForXPathExpression(PATE xecutionContextImpl.java:854)
    at com.adobe.workflow.pat.service.PATExecutionContextImpl.setProcessDataValue(PATExecutionCo ntextImpl.java:707)
    at com.adobe.workflow.pat.service.PATExecutionContextImpl.setProcessDataWithExpression(PATEx ecutionContextImpl.java:429)
    at com.adobe.workflow.qpac.set_value.SetValueService.execute(SetValueService.java:72)
    at com.adobe.workflow.engine.PEUtil.executeAction(PEUtil.java:184)
    at com.adobe.workflow.engine.ProcessEngineBMTBean.continueBranchAtAction(ProcessEngineBMTBea n.java:2371)
    at com.adobe.workflow.engine.ProcessEngineBMTBean.asyncInvokeProcessCommand(ProcessEngineBMT Bean.java:512)
    at sun.reflect.GeneratedMethodAccessor709.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:324)
    at org.jboss.ejb.StatelessSessionContainer$ContainerInterceptor.invoke(StatelessSessionConta iner.java:683)
    at org.jboss.resource.connectionmanager.CachedConnectionInterceptor.invoke(CachedConnectionI nterceptor.java:185)
    at org.jboss.ejb.plugins.AbstractTxInterceptor.invokeNext(AbstractTxInterceptor.java:84)
    at org.jboss.ejb.plugins.AbstractTxInterceptorBMT.invokeNext(AbstractTxInterceptorBMT.java:1 44)
    at org.jboss.ejb.plugins.TxInterceptorBMT.invoke(TxInterceptorBMT.java:62)
    at org.jboss.ejb.plugins.StatelessSessionInstanceInterceptor.invoke(StatelessSessionInstance Interceptor.java:72)
    at org.jboss.ejb.plugins.SecurityInterceptor.invoke(SecurityInterceptor.java:120)
    at org.jboss.ejb.plugins.LogInterceptor.invoke(LogInterceptor.java:191)
    at org.jboss.ejb.plugins.ProxyFactoryFinderInterceptor.invoke(ProxyFactoryFinderInterceptor. java:122)
    at org.jboss.ejb.StatelessSessionContainer.internalInvoke(StatelessSessionContainer.java:331 )
    at org.jboss.ejb.Container.invoke(Container.java:723)
    at org.jboss.ejb.plugins.local.BaseLocalProxyFactory.invoke(BaseLocalProxyFactory.java:359)
    at org.jboss.ejb.plugins.local.StatelessSessionProxy.invoke(StatelessSessionProxy.java:83)
    at $Proxy285.asyncInvokeProcessCommand(Unknown Source)
    at com.adobe.workflow.engine.ProcessCommandControllerBean.onMessage(ProcessCommandController Bean.java:127)
    at sun.reflect.GeneratedMethodAccessor641.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:324)
    at org.jboss.ejb.MessageDrivenContainer$ContainerInterceptor.invoke(MessageDrivenContainer.j ava:458)
    at org.jboss.resource.connectionmanager.CachedConnectionInterceptor.invoke(CachedConnectionI nterceptor.java:185)
    at org.jboss.ejb.plugins.MessageDrivenInstanceInterceptor.invoke(MessageDrivenInstanceInterc eptor.java:62)
    at org.jboss.ejb.plugins.AbstractTxInterceptor.invokeNext(AbstractTxInterceptor.java:84)
    at org.jboss.ejb.plugins.TxInterceptorCMT.runWithTransactions(TxInterceptorCMT.java:315)
    at org.jboss.ejb.plugins.TxInterceptorCMT.invoke(TxInterceptorCMT.java:148)
    at org.jboss.ejb.plugins.RunAsSecurityInterceptor.invoke(RunAsSecurityInterceptor.java:90)
    at org.jboss.ejb.plugins.LogInterceptor.invoke(LogInterceptor.java:191)
    at org.jboss.ejb.MessageDrivenContainer.internalInvoke(MessageDrivenContainer.java:372)
    at org.jboss.ejb.Container.invoke(Container.java:723)
    at org.jboss.ejb.plugins.jms.JMSCont

    Sorry, i just read my own message in the discussion forum and
    discovered all spaces for formating the XML tags where gone.
    It should look like this:
    [-----xml_type---]
    <doc>
    __<role>
    ____actor
    ____<first>
    ______john
    ____</first>
    ____<last>
    ______bond
    ____</last>
    __</role>
    __<role>
    ____actor
    ____<first>
    ______james
    ______</first>
    ____<last>
    ______smith
    ____</last>
    __</role>
    </doc>
    semantic:
    There are two actors: "john bond" and "james smith"
    Querying for "john bond" succeedes which is correct
    Querying for "james smith" succeedes which is correct
    Querying for "james bond" fails which is correct
    Querying for "john smith" succeedes which is an ERROR!
    contains(xdata, 'actor INPATH(//role[./first = "john" and ./last
    = "smith"])' (= 100 ---> ERROR!)
    bye,
    feri

  • How can I get String from Bytes

    I want to get String from array of bytes but i have some trouble from byte that it's lager more than 128. How can I do ???
    Please hepl me. Thanks very much.

    This program is only to show you what the relationships are between unsigned byte, signed byte, character, and binary values. Because of the constraints that Java has, the program code is not especially clean. Run the program and see if it helps. As has been said, the character output is dependent on the encoding in use.
    Here is a sample of some of its output:
    Unsigned byte= 189 Signed byte= -67 Character= � Binary= 10111101
    Unsigned byte= 190 Signed byte= -66 Character= � Binary= 10111110
    Unsigned byte= 191 Signed byte= -65 Character= � Binary= 10111111
    Unsigned byte= 192 Signed byte= -64 Character= � Binary= 11000000
    Unsigned byte= 244 Signed byte= -12 Character= � Binary= 11110100
    Unsigned byte= 245 Signed byte= -11 Character= � Binary= 11110101
    Unsigned byte= 246 Signed byte= -10 Character= � Binary= 11110110
    public class ATest {
        public static void main(String[] args) {
            int in;
            byte by;
            String bin;
            char chr;
            for(in=0; in<256; in++) {
                // create a byte whose binary value is equal to the;
                // integer loop counter;
                by = (byte)in;
                // mask off sign extension [that I don't agree with!] and;
                // cast the resultant 8 bits to a char;
                chr = (char)(by & 0x00ff);
                // since there's no Byte.toInteger, must cast to int to get;
                // binary string and then delete unwanted portion of string;
                if(in<128) {
                    bin = Integer.toBinaryString((int)by);
                } else {
                    bin = Integer.toBinaryString((int)by).substring(24);
                // print everything;
                System.out.println(
                    "Unsigned byte= "+in+
                    " Signed byte= "+by+
                    " Character= "+chr+
                    " Binary= "+bin);
    }

  • Imageicon created from byte array gives -1 height and -1 width...

    Hi,
    when I am trying to create an imageicon object from byte arrays the length and width of the object are coming to be -1.So I am unable to resize the image..
    This is happening for only few images, most of them are working fine and I can resize it...
    What possibly could be wrong??
    ImageIcon imageIcon = new ImageIcon(pImageData) where pImageData is bytearray..
    but I am getting imageIcon.getIconWidth()=-1
    and
    imageIcon.getIconHeight()=-1
    Can anyone help???

    es5f2000 wrote:
    I'm not sure if this is related, but I believe that images which are not currently being rendered return -1, -1 as their size.It is not even correct, so I'm confident it is not related.
    import java.awt.Image;
    import javax.swing.ImageIcon;
    import javax.imageio.ImageIO;
    import java.net.URL;
    class TestIconSize {
         public static void main(String[] args) throws Exception {
              Image image = ImageIO.read( new URL(
                   "http://forums.sun.com/im/silver-star.gif") );
              ImageIcon imageIcon = new ImageIcon( image );
              System.out.println( "Width: " + imageIcon.getIconWidth() );
              System.out.println( "Height: " + imageIcon.getIconHeight() );
    }Output.
    andrew@pc1:/media/disk/projects/numbered/all$ java TestIconSize
    Width: 16
    Height: 16
    andrew@pc1:/media/disk/projects/numbered/all$ The post after yours seems of even more dubious quality. For those (and other) reasons, I second Darryl's call for an SSCCE.

  • [svn] 4525: Fix loading RSLs from applications loaded from bytes.

    Revision: 4525
    Author: [email protected]
    Date: 2009-01-14 10:15:45 -0800 (Wed, 14 Jan 2009)
    Log Message:
    Fix loading RSLs from applications loaded from bytes.
    QE Notes: None
    Doc Notes: None
    Bugs: SDK-18250
    Reviewer: Alex
    tests: checkintests
    SystemManager.as
    Normalize the root urls passed into the RSLItems.
    LoaderUtil.as
    Test rootURL first before all the url tests. No need to perform all url tests if rootURL is null.
    Ticket Links:
    http://bugs.adobe.com/jira/browse/SDK-18250
    Modified Paths:
    flex/sdk/branches/3.3.0/frameworks/projects/framework/src/mx/managers/SystemManager.as
    flex/sdk/branches/3.3.0/frameworks/projects/framework/src/mx/utils/LoaderUtil.as

    Revision: 4525
    Author: [email protected]
    Date: 2009-01-14 10:15:45 -0800 (Wed, 14 Jan 2009)
    Log Message:
    Fix loading RSLs from applications loaded from bytes.
    QE Notes: None
    Doc Notes: None
    Bugs: SDK-18250
    Reviewer: Alex
    tests: checkintests
    SystemManager.as
    Normalize the root urls passed into the RSLItems.
    LoaderUtil.as
    Test rootURL first before all the url tests. No need to perform all url tests if rootURL is null.
    Ticket Links:
    http://bugs.adobe.com/jira/browse/SDK-18250
    Modified Paths:
    flex/sdk/branches/3.3.0/frameworks/projects/framework/src/mx/managers/SystemManager.as
    flex/sdk/branches/3.3.0/frameworks/projects/framework/src/mx/utils/LoaderUtil.as

  • Loading class from byte[]

    Hi,
    is there a way to load class (create object) from byte[] ?

    Yes. Look at ClassLoader. You will have to write your own subclass though many exist in other packages.

  • Re-construct the key from byte[]

    Hi,
    I am constructing the key as follows:
    KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
    keyGenerator.init(128);     
    Key key = keyGenerator.generateKey();
    I intend to use this key for Encryption/Decryption etc. Then, I am getting the byte[] of the key as follows:
    byte[] keyBytes = key.getEncoded();
    Now, it there any way to re-construct they original key from keyBytes.
    Any help in on this is highly appreciated.
    Thanks,
    Ajas.

    OK...
    I found the way...
    try {
    // Generate a key
    KeyGenerator keyGen = KeyGenerator.getInstance("DESede");
    SecretKey key = keyGen.generateKey();
    // Get the bytes of the key
    byte[] keyBytes = key.getEncoded();
    int numBytes = keyBytes.length;
    // The bytes can be converted back to a SecretKey
    SecretKey key2 = new SecretKeySpec(keyBytes, "DESede");
    boolean b = key.equals(key2); // true
    } catch (NoSuchAlgorithmException e) {

  • Play video from byte stream? (load video from local container / archive).

    I'd like to bundle video and other media items in a container / archive file and play it from an AIR app...  Essentially I'd like to make my own distribution format that supports video plus attached files, etc.
    So, coming from the Java world I thought I might be able to construct a stream and read the bytes from the correct part of my container file.  But I'm not sure if I can actually do that with the Flash APIs.  I see that the Video component works with NetConnection objects, but it's not clear to me if I can do anything with these.
    Can anyone tell me if what I want to do is possible?
    thanks,
    Pat

    You could probably use an SSLSocket to read the video file from an encrypted stream, save it as a file on the client machine, and then read the video from the file to the MediaPlayer if that's what you mean.

  • How Do I Load An Animated GIF Into PictureBox Control From Byte Array?

    I'm having a problem with loading an animated GIF int a picturebox control in a C# program after it has been converted to a base64 string, then converted to a byte array, then written to binary, then converted to a base64 string again, then converted to
    a byte array, then loaded into a memory stream and finally into a picturebox control.
    Here's the step-by-step code I've written:
    1. First I open an animated GIF from a file and load it directly into a picturebox control. It animates just fine.
    2. Next I convert the image in the picturebox control (pbTitlePageImage) to a base64 string as shown in the code below:
                    if (pbTitlePageImage.Image != null)
                        string Image2BConverted;
                        using (Bitmap bm = new Bitmap(pbTitlePageImage.Image))
                            using (MemoryStream ms = new MemoryStream())
                                bm.Save(ms, ImageFormat.Jpeg);
                                Image2BConverted = Convert.ToBase64String(ms.ToArray());
                                GameInfo.TitlePageImage = Image2BConverted;
                                ms.Close();
                                GameInfo.TitlePageImagePresent = true;
                                ProjectNeedsSaving = true;
    3. Then I write the base64 string to a binary file using FileStream and BinaryWriter.
    4. Next I get the image from the binary file using FileStream and BinaryReader and assign it to a string variable. It is now a base64 string again.
    5. Next I load the base64 string into a byte array, then I load it into StreamReader and finally into the picturebox control (pbGameImages) as shown in the code below:
    byte[] TitlePageImageBuffer = Convert.FromBase64String(GameInfo.TitlePageImage);
                            MemoryStream memTitlePageImageStream = new MemoryStream(TitlePageImageBuffer, 0, TitlePageImageBuffer.Length);
                            memTitlePageImageStream.Write(TitlePageImageBuffer, 0, TitlePageImageBuffer.Length);
                            memTitlePageImageStream.Position = 0;
                            pbGameImages.Image = Image.FromStream(memTitlePageImageStream, true);
                            memTitlePageImageStream.Close();
                            memTitlePageImageStream = null;
                            TitlePageImageBuffer = null;
    This step-by-step will work with all image file types except animated GIFs (standard GIFs work fine). It looks like it's just taking one frame from the animation and loading it into the picturebox. I need to be able to load the entire animation. Does any of
    the code above cause the animation to be lost? Any ideas?

    There is an ImageAnimator so you may not need to use byte array instead.
    ImageAnimator.Animate Method
    http://msdn.microsoft.com/en-us/library/system.drawing.imageanimator.animate(v=vs.110).aspx
    chanmm
    chanmm

  • Help needed in understanding conversion alghorithm from byte to hex

    Hi, I'm studying the following code:
    public static char[] byteToHex(byte[] data) {
      char[] retValue = new char[data.length * 2];
      int value = 0;
      int highIndex = 0;
      int lowIndex = 0;
      for (int i = 0; i < retValue.length; i++) {
        value = (data[i] + 256) % 256;
        highIndex = value >> 4;
        lowIndex = value & 0x0f;
        retValue[i * 2 + 0] = hexTable[highIndex];
        retValue[i * 2 + 1] = hexTable[lowIndex];
      return retValue;
    }There are few things (the most important) which I don't understand about the above code.
    I understood that what's returned has got double size related to what's passed in because a char takes 16 bits while a byte takes 8.
    1) I don't understand why each byte must be first added 256 and then % with 256 (returning the same value - Is this to eliminate negative values?)
    2) I do understand that each byte is transformed in two hexadecimal values: one is the highIndex (first 8 bits) and the second is the lowerIndex (last 8 bits) and that each value is tranformed in its hexadecimal value from the array of hex values.
    3) What I don't really understand is why the highIndex is calculated as: value >> 4
    and the lowest index is calculated as value 0x0f (is this last also to eliminate negative values?)
    If someone could clarify this for me, I'd be very grateful.
    Thanks.
    Marco

    So, does this mean that we add 256 to eliminate the sign?No. You need the whole line to convert a signed byte into an int between 0 and 255.
    A simpler way to do this would be
    value = data[i] & 0xFF;
    This moves down the higher bits so that it turnsinto lower bits. i.e. we need it to >be between 0 and
    15.
    Is this shifted of 4 because Math.pow(2, 4) = 16.0?Doing in this case, x >>4 is the same as x / 16
    This leaves only the lowest 4 bits.Is the following what happens?There are no char values produced. Using 0000 as an example is not a good idea as you can change it in many ways and it is still 0000
    >
    Received as initial value:
    byte: 0000 0000
    What we need to obtain:
    char: 0000 0000 0000 0000
    The first 4 bits of the above byte are shifted of 4
    positions to find the hexadecimal equivalent (if from
    2 I want to get to 16 I have to do the opposite of
    powering a number by 4); The last four bits of the
    byte are extracted because of the '&' operator with
    0x0f (which in binary is 1111 - Therefore all the '1'
    are kept)?Yes.

  • Create image from byte[]array on server side

    Hello everyone..
    I'm developing an application which will take snapshots from a mobile device, and send it to my pc via bluetooth. I have my own midlet which uses the phone camera to take the snapshot, i want to transfer that snapshot to my pc.
    The snapshot is taken is stored in an array byte.
    The image can be created on the phone itself with no problem using : image.createImage(byte[])
    my problem is that when i send the array byte via bluetooth, and receive it on the server, i cannot create the image using the :image.createImage() code
    The connection is good since i have tested by writing the content of the array in a text file.
    Piece of midlet code:
                try{
                     stream = (StreamConnection)Connector.open(url);
                     OutputStream ggt = stream.openOutputStream();
                     ggt.write(str);
                     ggt.close();
                }catch(Exception e){
                     err1  = e.getMessage();
                }where str is my array byte containing the snapshot
    And on my server side:
    Thread th = new Thread(){
                   public void run(){
                        try{
                             while(true){
                                  byte[] b = new byte[in.read()];
                                  int x=0;
                                  System.out.println("reading");
                                  r = in.read(b,0,b.length);
                                  if (r!=0){
                                       System.out.println(r);     
                                       img = Image.createImage(b, 0, r);
                                                            //other codes
                                       i get this error message:
    Exception in thread "Thread-0" java.lang.UnsatisfiedLinkError: javax.microedition.lcdui.ImmutableImage.decodeImage([BII)V
         at javax.microedition.lcdui.ImmutableImage.decodeImage(Native Method)
         at javax.microedition.lcdui.ImmutableImage.<init>(Image.java:906)
         at javax.microedition.lcdui.Image.createImage(Image.java:367)
         at picserv2$1.run(picserv2.java:70)
    Please anyone can help me here? is this the way to create the image on the server side? thx a lot

    here is exactly how i did it :
    while(true){
                                  byte[] b = new byte[in.read()];
                                  System.out.println("reading");
                                  r = in.read(b, 0, b.length);
                                  if (r!=0){
                                       Toolkit toolkit = Toolkit.getDefaultToolkit();
                                       Image img = toolkit.createImage(b, 0, b.length);
                                       JLabel label = new JLabel(new ImageIcon(img) );
                                       BufferedImage bImage = new BufferedImage(img.getWidth(label),img.getHeight(label),BufferedImage.TYPE_INT_RGB);
                                       bImage.createGraphics().drawImage(img, 0,0,null);
                                       File xd = new File("D:/file.jpg");
                                       ImageIO.write(bImage, "jpg", xd);
                                       System.out.println("image sent");
                             }Edited by: jin_a on Mar 22, 2008 9:58 AM

Maybe you are looking for