Concatenate byte arrays

I have a Socket that is sending data accross a connection. I want to keep reading more data into an array. Is there a way to add more data into an array, or do I have to create a new one every time.
I'd like to do something like this:
byte[] b = new byte[10];
istrm.read( b2);
b += b2; <----- I know this doesn't work
I have been writing it like this:
InputStream istrm = sock.getInputStream();
byte[] b = new byte[ istrm.available()];
istrtrm.read( b);
but I don't know if that gets all of the data. If it blocks for a while, does that mean more data will come down the stream? I just want to make sure the data all gets there and put into 1 byte array.
Thanks in advance.

You cannot alter the size of an array object. You must allocate another array and copy the contents from the original. A better way would probably be to have a list of arrays, keeping track of the total received. THen create a single array and copy the data from the smaller arrays. You could have this happen whenever the list length exceeds a chosen boundary to avoid having too many small array objects referenced in memory.
eg
byte[] b1 = new byte[100];
byte[] b2 = new byte[50];
List list = new LinkedList();
int totalSize = 0;
list.add(b1);
totalSize += b1.length();
list.add(b2);
totalSize += b2.length();
byte[] b = new byte[totalSize];
int currentPos = 0;
for(Iterator iterator = list.iterator(); iterator.hasNext(); )
byte[] temp = (byte[]) iterator.next();
for(int count = 0; count < temp.length; count++)
b[currentPos++] = temp[count];
or something like that... (untested)
Hope that helps...
Talden

Similar Messages

  • Unable to merge two byte arrays

    Hi there,
    I am trying to merge two byte arrays into one byte array
    and write into a new word document using OutputStream object.
    But in the new word document that is created only the contents
    of the first byte array are being shown and not that of the second one.
    I have pasted the code below.
    Any pointers will be of great help.
    Thanks and Regards,
    Partha.
    package com.cisco.asit.icn.common.servlets;
    import java.io.ByteArrayInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import org.apache.poi.hwpf.HWPFDocument;
    import org.apache.poi.poifs.filesystem.POIFSFileSystem;
    public class TestPOC {
         public static void main(String[] args) {
              try
                   System.out.println("I am here...");
                   System.out.println("I am in example 4...");
                   byte[] byteAr1 = getBytesFromFile(new File("c:\\Testing_POC\\Not_blank.doc"));
                   System.out.println(byteAr1.toString());
                   System.out.println();
                   byte[] byteAr2 = getBytesFromFile(new File("c:\\Testing_POC\\Quest.doc"));
                   byte[] finalOne = concatenate(byteAr1, byteAr2);
                   System.out.println("byte array 1..."+ byteAr1.length);
                   System.out.println("byte array 2..."+ byteAr2.length);
                   System.out.println("Final byte array ..."+ finalOne.length);
                   InputStream is = new ByteArrayInputStream(finalOne);
                   POIFSFileSystem fss = new POIFSFileSystem(is);
                   OutputStream out1 = new FileOutputStream("c:\\Testing_POC\\Result.doc");
                   fss.writeFilesystem(out1);
                   System.out.println("Stored to file system...");
                   try {
                        Runtime.getRuntime().exec("rundll32 SHELL32.DLL,ShellExec_RunDLL \"" + "c:\\Testing_POC\\Result.doc");
                   catch (IOException e1){
                        e1.printStackTrace();
                   System.out.println("I am fine till here...");
         out1.flush();
         out1.close();
         catch (Throwable t) {
         t.printStackTrace();
         byte[] res = new byte[l.length + r.length];
         System.arraycopy(l, 0, res, 0, l.length);
         System.arraycopy(r, 0, res, l.length ,r.length);
    return res;
         public static byte[] getBytesFromFile(File file) throws IOException {
    InputStream is = new FileInputStream(file);
    // Get the size of the file
    long length = file.length();
    // You cannot create an array using a long type.
    // It needs to be an int type.
    // Before converting to an int type, check
    // to ensure that file is not larger than Integer.MAX_VALUE.
    if (length > Integer.MAX_VALUE) {
    // File is too large
    // Create the byte array to hold the data
    byte[] bytes = new byte[(int)length];
    // Read in the bytes
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length
    && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
    offset += numRead;
    // Close the input stream and return bytes
    is.close();
    return bytes;
    }

    parthInfy wrote:
    Hi there,
    I am trying to merge two byte arrays into one byte array
    and write into a new word document using OutputStream object.
    But in the new word document that is created only the contents
    of the first byte array are being shown and not that of the second one.
    Because the end of the first byte array contains a "document ending" tag and anything after that is just flotsam. And, even if you could remove that "document ending" tag, there is for the second a "document begin" tag. (Among many other tags and flags in both documents.) Word (ar just about any) documents are not simple text files to be concatented, truncated, twisted, inverted, or whatever else, at your pleasure. You actually, God forbid, have to kinow what you're doing, to manipulate them at this level. And, surprise, surprise, you don't.
    Edit: Google "POI"

  • 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

  • Convert XML data to byte array...

    Hello All,
    In my application, i have an XML file and the corresponding XSD file. This XML file is having some date, which i want to convert into an byte[] and then save it in a file. 
    How i can convert the XML data in the byte[]? Here as an example of the xml file and the byte[] data which i want to save in a file.
    <?xml version="1.0" encoding="utf-8"?>
    <HeadersInfo>
    <header>
    <id>0</id>
    <Name>H1</Name>
    </header>
    <header>
    <id>1</id>
    <Name>H2</Name>
    </header>
    </HeasersInfo>
    In the above example 'id' field is of type 'uint' and 'name' field is of type 'string' with max length of '5'. So in this case my byte array should be as shown below:
    00 00 00 01 48 31 00 00 00
    00 00 00 02 48 32 00 00 00
    Here underlines values are for the 'id' parameter where as values in bold are for 'Name' parameter for all the header values in sequence. Name parameter is null (0x00) padded.
    Thanks in advance,
    IamHuM

    Hi,
    the following example extract the id, name values using LINQ To Xml and writes it to a memory stream using a binary writer and returns the result as a byte array:
    internal static byte[] GetXmlAsByteArray()
    var document = XDocument.Parse("<HeadersInfo>"
    + " <header><id>1</id><Name>H1</Name></header>"
    + " <header><id>2</id><Name>H2</Name></header>"
    // additional testing
    + " <header><id>32767</id><Name>H1234</Name></header>"
    + " <header><id>305419896</id><Name>H56789</Name></header>"
    + "</HeadersInfo>");
    const int NameLength = 5; // Max length for a name
    byte[] zeroBytes = new byte[NameLength]; // Helper to fill name
    using (var ms = new MemoryStream())
    using (var writer = new BinaryWriter(ms))
    // write each header
    foreach (var header in document.Root.Elements("header"))
    int id = (int)header.Element("id");
    string name = (string)header.Element("Name");
    byte[] nameBytes = System.Text.Encoding.UTF8.GetBytes(name);
    Console.WriteLine("id: {0}, Name: {1}", id, name);
    // Write id
    writer.Write(GetUIntBytes((uint)id));
    // Write name NameLength (5) max, otherwise padded
    if (nameBytes.Length > NameLength)
    writer.Write(nameBytes, 0, NameLength);
    else
    writer.Write(nameBytes, 0, nameBytes.Length);
    if (nameBytes.Length < NameLength)
    writer.Write(zeroBytes, 0, NameLength - nameBytes.Length);
    byte[] result = ms.ToArray();
    // dump array
    foreach (var value in result)
    Console.Write("{0:X2} ", value);
    Console.WriteLine();
    return result;
    public static byte[] GetUIntBytes(uint value)
    if (BitConverter.IsLittleEndian)
    // swap bytes
    value = ((value & 0x00ff) << 24)
    | ((value & 0xff00) << 8)
    | ((value & 0x00ff0000) >> 8)
    | ((value & 0xff000000) >> 24);
    return BitConverter.GetBytes(value);
    For a general purpose solution you should create a class and split the example into separate methods to extract the data and write the values (integers, strings).
    Regards, Elmar

  • Convert byte array to table of int

    [http://www.codeproject.com/KB/database/PassingArraysIntoSPs.aspx?display=Print|http://www.codeproject.com/KB/database/PassingArraysIntoSPs.aspx?display=Print] Hello friends.
    I'm pretty new with PL/SQL.
    I have code that run well on MSSQL and I want to convert it to PL/SQL with no luck.
    The code converts byte array to table of int.
    The byte array is actually array of int that was converted to bytes in C# for sending it as parameter.
    The TSQL code is:
    CREATE FUNCTION dbo.GetTableVarchar(@Data image)
    RETURNS @DataTable TABLE (RowID int primary key IDENTITY ,
    Value Varchar(8000))
    AS
    BEGIN
    --First Test the data is of type Varchar.
    IF(dbo.ValidateExpectedType(103, @Data)<>1) RETURN
    --Loop thru the list inserting each
    -- item into the variable table.
    DECLARE @Ptr int, @Length int,
    @VarcharLength smallint, @Value Varchar(8000)
    SELECT @Length = DataLength(@Data), @Ptr = 2
    WHILE(@Ptr<@Length)
    BEGIN
    --The first 2 bytes of each item is the length of the
    --varchar, a negative number designates a null value.
    SET @VarcharLength = SUBSTRING(@Data, @ptr, 2)
    SET @Ptr = @Ptr + 2
    IF(@VarcharLength<0)
    SET @Value = NULL
    ELSE
    BEGIN
    SET @Value = SUBSTRING(@Data, @ptr, @VarcharLength)
    SET @Ptr = @Ptr + @VarcharLength
    END
    INSERT INTO @DataTable (Value) VALUES(@Value)
    END
    RETURN
    END
    It's taken from http://www.codeproject.com/KB/database/PassingArraysIntoSPs.aspx?display=Print.
    The C# code is:
    public byte[] Convert2Bytes(int[] list)
    if (list == null || list.Length == 0)
    return new byte[0];
    byte[] data = new byte[list.Length * 4];
    int k = 0;
    for (int i = 0; i < list.Length; i++)
    byte[] intBytes = BitConverter.GetBytes(list);
    for (int j = intBytes.Length - 1; j >= 0; j--)
    data[k++] = intBytes[j];
    return data;
    I tryied to convert the TSQL code to PL/SQL and thats what I've got:
    FUNCTION GetTableInt(p_Data blob)
    RETURN t_array --t_array is table of int
    AS
    l_Ptr number;
    l_Length number;
    l_ID number;
    l_data t_array;
    BEGIN
         l_Length := dbms_lob.getlength(p_Data);
    l_Ptr := 1;
         WHILE(l_Ptr<=l_Length)
         loop
              l_ID := to_number( DBMS_LOB.SUBSTR (p_Data, 4, l_ptr));
              IF(l_ID<-2147483646)THEN
                   IF(l_ID=-2147483648)THEN
                        l_ID := NULL;
                   ELSE
                        l_Ptr := l_Ptr + 4;
                        l_ID := to_number( DBMS_LOB.SUBSTR(p_Data, 4,l_ptr));
                   END IF;
                   END IF;
    l_data(l_data.count) := l_ID;
              l_Ptr := l_Ptr + 4;
         END loop;
         RETURN l_data;
    END GetTableInt;
    This isn't work.
    This is the error:
    Error report:
    ORA-06502: PL/SQL: numeric or value error: character to number conversion error
    06502. 00000 - "PL/SQL: numeric or value error%s"
    I think the problem is in this line:
    l_ID := to_number( DBMS_LOB.SUBSTR (p_Data, 4, l_ptr));
    but I don't know how to fix that.
    Thanks,
    MTs.

    I'd found the solution.
    I need to write:
    l_ID := utl_raw.cast_to_binary_integer( DBMS_LOB.SUBSTR(p_Data, 4,l_ptr));
    instead of:
    l_ID := to_number( DBMS_LOB.SUBSTR (p_Data, 4, l_ptr));
    The performance isn't good, it's take 2.8 sec to convert 5000 int, but it's works.

  • Converting ASCII text (byte array ending in null) to a String

    Hi all,
    I am trying to convert a null terminated ascii string stored in a byte array to a java String. When I pass the byte array to the String constructor it
    does not detect/interpret the null as a terminator for the ascii string. Is this something I have to manually program in? ie Check for where the null is and then
    pass that subarray of everything before the null to the String constructor?
    example of problem
    //               A   B  C   D   null   F   (note F is junk in the array, and should be ignored since it is after null)
    byte[] asciiArray = { 65, 66, 67, 68, 0,  70 };
    System.out.println(new String(asciiArray, "UTF-8"));
    //this prints ABCD"sqare icon"F

    Why do you expect the null character to terminate the string? If you come from a C or C++ background, you need to understand that java.lang.String is not just a mere character array. It's a full-fledged Java object that knows its length without having any need for null terminator. So Ascii 0 is just another character for String object. To achieve what you want to do, you have to manually loop through the byte array and stop when you encounter a null character.

  • How do I read directly from file into byte array

    I am reading an image from a file into a BuffertedImage then writing it out again into an array of bytes which I store and use later on in the program. Currently Im doing this in two stages is there a way to do it it one go to speed things up.
    try
                //Read File Contents into a Buffered Image
                /** BUG 4705399: There was a problem with some jpegs taking ages to load turns out to be
                 * (at least partially) a problem with non-standard colour models, which is why we set the
                 * destination colour model. The side effect should be standard colour model in subsequent reading.
                BufferedImage bi = null;
                ImageReader ir = null;
                ImageInputStream stream =  ImageIO.createImageInputStream(new File(path));
                final Iterator i = ImageIO.getImageReaders(stream);
                if (i.hasNext())
                    ir = (ImageReader) i.next();
                    ir.setInput(stream);
                    ImageReadParam param = ir.getDefaultReadParam();
                    ImageTypeSpecifier typeToUse = null;
                    for (Iterator i2 = ir.getImageTypes(0); i2.hasNext();)
                        ImageTypeSpecifier type = (ImageTypeSpecifier) i2.next();
                        if (type.getColorModel().getColorSpace().isCS_sRGB())
                            typeToUse = type;
                    if (typeToUse != null)
                        param.setDestinationType(typeToUse);
                    bi = ir.read(0, param);
                    //ir.dispose(); seem to reference this in write
                    //stream.close();
                //Write Buffered Image to Byte ArrayOutput Stream
                if (bi != null)
                    //Convert to byte array
                    final ByteArrayOutputStream output = new ByteArrayOutputStream();
                    //Try and find corresponding writer for reader but if not possible
                    //we use JPG (which is always installed) instead.
                    final ImageWriter iw = ImageIO.getImageWriter(ir);
                    if (iw != null)
                        if (ImageIO.write(bi, ir.getFormatName(), new DataOutputStream(output)) == false)
                            MainWindow.logger.warning("Unable to Write Image");
                    else
                        if (ImageIO.write(bi, "JPG", new DataOutputStream(output)) == false)
                            MainWindow.logger.warning("Warning Unable to Write Image as JPEG");
                    //Add to image list
                    final byte[] imageData = output.toByteArray();
                    Images.addImage(imageData);
                  

    If you don't need to manipulate the image in any way I would suggest you just read the image file directly into a byte array (without ImageReader) and then create the BufferedImage from that byte array.

  • How do I get a byte array from an object passed into the JNI?

    This is what my java code looks like:
    public class streamedData
    protected byte[] m_value = null;
    public byte[] getByteArray ()
    return m_value;
    /* code not pertaining to this question snipped. */
    jclass streamedDataClass = env->GetObjectClass(jstreamedData);
    // Get methodIDs for the various NPKI_Extension methods
    value = env->GetMethodID(streamedDataClass, "getByteArray", "()[B");
    lstreamedData->value = (unsigned char *)malloc (lstreamedData->length);
    if (lstreamedData->value == NULL)
    return INSUFFICIENT_MEMORY;
    memset (lstreamedData->value, 0, lstreamedData->length);
    memcpy (lstreamedData->value, env->CallByteMethodA(streamedDataClass, value, NULL), lstreamedData->length);
    This is not working.
    My question is, how do I get a copy of or read m_value in the JNI layer? Do I have to make the byte array public and access it as a field ID?
    Any help would be appreciated. Why oh why can't there be a CallByteArrayMethod????

    My question is, how do I get a copy of or read m_value in the JNI layer? Do I have to make the byte array public and access it as a field ID?
    You can retrieve a handle to the byte array, through a method call, as you're doing now, or by directly accessing it through GetFieldID.
    In the case of the method call, you'll want to do:jmethodID getByteArrayMethod = env->GetMethodID(streamedDataClass, "getByteArray", "()[B");
    jbyteArray byteArray = static_cast<jbyteArray>( env->CallObjectMethod( jstreamedData, getByteArrayMethod ) );In the case of field access, you can do:jfieldID m_valueFieldID = env->GetFieldID( streamedDataClass, "m_value", "[B" );
    jbyteArray byteArray = static_cast<jbyteArray>( env->GetObjectField( jstreamedData, m_valueFieldID ) );Once you have byteArray, you need to access it using the array operations:lstreamedData->value = env->GetByteArrayElements( byteArray, 0 );
    // Do what you want to do, then release the array
    env->ReleaseByteArrayElements( byteArray, lstreamedData->value, 0 );As always, Jace, http://jace.reyelts.com/jace, makes this easier. For example,void printByteArray( jobject jstreamedData ) {
      streamedData data( jstreamedData );
      JArray<JByte> byteArray = streamedData.m_value();
      for ( int i = 0; i < byteArray.length(); ++i ) {
        cout << byteArray[ i ];
    }God bless,
    -Toby Reyelts

  • How do I store an Int, a short, and multiple bytes from file in byte array

    I'm attempting to do this for a project but can't figure out how to store the three values in one byte array. This is what i've tried
    public void send(byte[] input)
              // TODO
              ByteArrayInputStream bais = new ByteArrayInputStream(input);
              ByteArrayOutputStream baos = new ByteArrayOutputStream();
              DataOutputStream dos = new DataOutputStream(baos);
              byte[] pData = new byte[100];
              try {
                   dos.writeShort(checkSum);
                   dos.writeInt(nextSeqNum);
                   pData=baos.toByteArray();
                   bais.read(pData);
              } catch (IOException e) {
              DatagramPacket dgp = new DatagramPacket(pData, pData.length);When i set pData=baos.toByteArray() it changes the size and then stops me from being able to read the other 94 bytes into the array to send. Any ideas?

    You don't need the ByteArrayInputStream at all.
    dos.writeShort(checkSum);
    dos.writeInt(nextSeqNum);
    dos.write(input);
    pData = baos.toByteArray();
    When i set pData=baos.toByteArray() it changes the sizeNo, it makes it refer to a new byte[] array containing what you've written to the BAOS. That's what it's supposed to do.

  • How to get a string or byte array representation of an Image/BufferedImage?

    I have a java.awt.Image object that I want to transfer to a server application (.NET) through a http post request.
    To do that I would like to encode the Image to jpeg format and convert it to a string or byte array to be able to send it in a way that the receiver application (.NET) could handle. So, I've tried to do like this.
    private void send(Image image) {
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        try {
            BufferedImage buffImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            ImageIcon imageIcon = new ImageIcon(image);
            ImageObserver observer = imageIcon.getImageObserver();
            buffImage.getGraphics().setColor(new Color(255, 255, 255));
            buffImage.getGraphics().fillRect(0, 0, width, height);
            buffImage.getGraphics().drawImage(imageIcon.getImage(), 0, 0, observer);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(stream);
            jpeg.encode(buffImage);
            URL url = new URL(/* my url... */);
            URLConnection connection = url.openConnection();
            String boundary = "--------" + Long.toHexString(System.currentTimeMillis());
            connection.setRequestProperty("method", "POST");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            String output = "--" + boundary + "\r\n"
                          + "Content-Disposition: form-data; name=\"myImage\"; filename=\"myFilename.jpg\"\r\n"
                          + "Content-Type: image/jpeg\r\n"
                          + "Content-Transfer-Encoding: base64\r\n\r\n"
                          + new String(stream.toByteArray())
                          + "\r\n--" + boundary + "--\r\n";
            connection.setDoOutput(true);
            connection.getOutputStream().write(output.getBytes());
            connection.connect();
        } catch {
    }This code works, but the image I get when I save it from the receiver application is distorted. The width and height is correct, but the content and colors are really weird. I tried to set different image types (first line inside the try-block), and this gave me different distorsions, but no image type gave me the correct image.
    Maybe I should say that I can display the original Image object on screen correctly.
    I also realized that the Image object is an instance of BufferedImage, so I thought I could skip the first six lines inside the try-block, but that doesn't help. This way I don't have to set the image type in the constructor, but the result still is color distorted.
    Any ideas on how to get from an Image/BufferedImage to a string or byte array representation of the image in jpeg format?

    Here you go:
      private static void send(BufferedImage image) throws Exception
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpeg", byteArrayOutputStream);
        byte[] imageByteArray = byteArrayOutputStream.toByteArray();
        URL url = new URL("http://<host>:<port>");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(imageByteArray, 0, imageByteArray.length);
        outputStream.close();
        connection.connect();
        // alternative to connect is to get & close the input stream
        // connection.getInputStream().close();
      }

  • Send byte array argeument from pl/sql to java stored procedure?

    I have a java method that accepts an argument of type byte[].
    I want to define a call specification so that it can invoked from a sql statement.
    The Java Developer's Guide show how to map SQL data types to java types and classes, but it is unclear if I can map a SQL data type to an array.
    Does anyone know which SQL type to use to map to a byte array?
    I'm using Oracle 10.2, thus jvm 1.4.2.

    As soon as I posted this question, I saw the RAW to byte[] mapping listed in the documentation. How did I overlook it? Anyway, that what I needed.

  • How to send byte array and String values to servlet from Swing application

    Hi all,
    I am new to swing, servlet, and socket connection.
    I have swing application to draw images and some input data. I dont know to send to server.
    byte[] buf = baos.toByteArray();
    URL servletURL = new URL("http://10.70.70.1:8080/servlet/SaveImage)
    URLConnection conn = servletURL.openConnection();
    conn.setDoOutput(true);
    BufferedWriter out = new BufferedWriter( new OutputStreamWriter( conn.getOutputStream() ) );
    out.write(buf&a=aaaa&b=bbbbb);
    out.flush();
    out.close();
    can I do like this. Strings are received in server side perfect. but i cant get byte array data. Please help me.
    Thanks in advance.

    <img src="myservlet">
    In your myservlet:
    response.setContentType("image/jpeg");
    then write your image date via ImageIO that uses response output stream.

  • Error when creating BufferedImage with IndexColorModel from a byte array.

    Hi, I have a 1-dimentional byte array and an IndexColorTable, and I can't figure out how to combine the 2 into an BufferedImage without unnecessary copying/reallocating of the image buffer.
    The color model I have is:
    int [] cmap = new int [numColors];
    cmap[i++] = 0xffa0f000;  /etc.
    new IndexColorModel(8, 22, cmap, 0, true,  transparentIndex,  DataBuffer.TYPE_BYTE );Thanks for your help
    -Ben
    Ps.
    I've was looking at some example code (http://javaalmanac.com/egs/java.awt.image/Mandelbrot2.html?l=rel), and can't figure out how to go from the color model they're using to the one I have (the 8 bit one specified above). When I replace the 4bit colormodel in the code below with the 8bit color model specified above, I get the following error:
    [java] java.lang.IllegalArgumentException: Raster ByteInterleavedRaster: width = 5120 height = 3520 #numDataElements 1 dataOff[0] = 0 is incompatible with ColorModel IndexColorModel: #pixelBits = 8 numComponents = 4 color space = java.awt.color.ICC_ColorSpace@c51355 transparency = 2 transIndex = 22 has alpha = true isAlphaPre = false
    [java] at java.awt.image.BufferedImage.<init>(BufferedImage.java:613)
    Code:
    byte[] pixelArray = (byte[]) getData_CHAR();                
    int width = 5120;
    int height = 3520;
    int numbytes = width*height;
    //create DataBuffer using byte buffer of pixel data.
    DataBuffer dataBuffer = new DataBufferByte(pixelArray, numbytes, 0);
    //prepare a sample model that specifies a storage 8-bits of pixel data in an 8-bit data element
    int bitMasks[] = new int[]{0xf};
    SinglePixelPackedSampleModel sampleModel = new SinglePixelPackedSampleModel(DataBuffer.TYPE_BYTE, width, height, bitMasks);
    //create a raster using the sample model and data buffer
    WritableRaster writableRaster = Raster.createWritableRaster(sampleModel, dataBuffer, new Point(0,0));
    //generate 16-color model
    byte[] r = new byte[16];
    byte[] g = new byte[16];
    byte[] b = new byte[16];
    r[0] = 0; g[0] = 0; b[0] = 0;
    r[1] = 0; g[1] = 0; b[1] = (byte)192;
    r[2] = 0; g[2] = 0; b[2] = (byte)255;
    r[3] = 0; g[3] = (byte)192; b[3] = 0;
    r[4] = 0; g[4] = (byte)255; b[4] = 0;
    r[5] = 0; g[5] = (byte)192; b[5] = (byte)192;
    r[6] = 0; g[6] = (byte)255; b[6] = (byte)255;
    r[7] = (byte)192; g[7] = 0; b[7] = 0;
    r[8] = (byte)255; g[8] = 0; b[8] = 0;
    r[9] = (byte)192; g[9] = 0; b[9] = (byte)192;
    r[10] = (byte)255; g[10] = 0; b[10] = (byte)255;
    r[11] = (byte)192; g[11] = (byte)192; b[11] = 0;
    r[12] = (byte)255; g[12] = (byte)255; b[12] = 0;
    r[13] = (byte)80; g[13] = (byte)80; b[13] = (byte)80;
    r[14] = (byte)192; g[14] = (byte)192; b[14] = (byte)192;
    r[15] = (byte)255; g[15] = (byte)255; b[15] = (byte)255;
    //create buffered image    
    ColorModel colorModel = new IndexColorModel(4, 16, r, g, b);
    BufferedImage image = new BufferedImage(colorModel, writableRaster, false, null);Message was edited by:
    ben_weisburd
    Message was edited by:
    ben_weisburd

    I had the same problem too.
    anyone found the solution for this problem?
    thanks
    Bruno Rabino
    When I try to make a MD-form, where the base-table for the detail contains a column with a BLOB-datatype. I get following error when I finish creation of the form.
    Error: Exception from wwv_generate_component.build_procedure (WWV-01821)
    Error creating module: ORA-01403: no data found (WWV-16042)
    When I use the table with the BLOB as master or in a form, it works fine.
    Has anyone else experienced this problem? Or knows a way to fix or work around it. Thanks in advance.
    Portal version: 3.0.6.6.5
    null

  • Sending publickey through the network as a byte array.

    I send client public key form server to client as a byte array through the network. I'm sruggling when I get that byte array from client side and again assign to the PublicKey variable. Anyone can give me any hints how can I extract the public key from the byte array.
    Thank you

    If your public key is from an X509 certificate, you can use the X509EncodedKeySpec class.

  • Sending a Byte array through a socket

    Can someone please tell me how i can send a Byte array from a client to a sever using sockets?
    Thanks
    Mark

    This tutorial should do the trick:
    http://java.sun.com/docs/books/tutorial/networking/sockets/index.html

Maybe you are looking for

  • Error while executing reports on 0FIGL_M30

    Hello, I am not able to check data in the MultiProvider 0FIGL_M30 and hence the reports are containing no data. This multiprovider is based on 2 infoproviders 0FIGL_V30 and 0FIGL_V31 which in turn get data from 0FIGL_M20. Now my problem is the report

  • XMP panels not showing up in CC

    We created custom XMP panels before. I now want them to show up in CC. I can get the tab open to show the file (this happens when I "Get Info" on the InDesign page), but it crashes InDesign and won't show the fields. Do I need to update the Flash fil

  • Material procurement type

    Hi All, For one material my client create with the procurement type F wrongly. then they need to change the procurement type as E. but we found that field is grayed. how to chage the field to enterable and we need to change the procurement type thank

  • App sign in

    When I sign in to update my App Store it signs me in under my wife's account. I can't change it to allow me to sign in under my account. how can I fix this?

  • Image MouseOver

    Hi - I have a image slider movie setup. When a user mouse's over the image I have a tooltip appear. I want the tooltip to contain the value of the "desc" value stored in the XMLfile. How can I determine which image is moused over? Is there an ID tied