Writing empty byte array to outputstream

Does anyone know if writing an empty byte array to an outputstream will throw an IOException? I think a little bug in my code is causing this because all seems to work when the byte array is not empty.
Thanks in advance for any help.

The (overridden) method write(byte[]) of java.io.OutputStream throws a java.lang.NullPointerException rather than java.io.IOException when byte[] is simply null.

Similar Messages

  • How to load and display a byte array (jpeg) image file dynamically in Flex?

    My web service client (servlet) received a binary jpeg data from an Image Server. The Flex application invokes the
    servlet via HttpService and receives the binary jpeg data as byte array.  How could it be displayed dynamically
    without writing the byte array to a jpeg file?  Please help (some sample code is very much appreciated).

    JPEGEncoder is only useful for converting BitmapData to ByteArray, not the other way around.
    By the way JPEGEncoder and PNGEncoder are part of the Flex SDK now, so no need to use AS3Lib (alltough it's a good library to have around).
    To display/use a ByteArray as image, use a Loader instance with the loadBytes method.
        Loader.loadBytes(bytes:ByteArray, context:LoaderContext = null);
    Listen for the complete event on the Loader.contentLoaderInfo and get the BitmapData in the event handler.
    private function loadJpeg():void {
        var loader:Loader = new Loader();
        loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderCompleteHandler);
        //jpgBA is the ByteArray loaded from webservice
        loader.loadBytes(jpgBA);
    private function loaderCompleteHandler(evt:Event):void {
        var t:LoaderInfo = evt.currentTarget as LoaderInfo;
        // display the jpeg in an Image component
        img.source = t.content;
    <mx:Image id="img" scaleContent="false" />

  • Reading in any file and converting to a byte array

    Okay what I am trying to do is to write a program that will read in any file and convert it into a int array so that I can then manipulate the values of the int array and then re-write the file. Once I get the file into an int array I want to try and compress the data with my own algorithm as well as try to write my own encryption algorithm.
    What I have been looking for is code samples that essentially read in the file as a byte array and then I have been trying to convert that byte array into an int array which I could then manipulate. So does anyone have any sample code that essentially takes a file and converts it into an int array and then converts it back into a byte array and write the file. I have found code that is close but I guess I am just too new to this. Any help would be appreciated.

    You can read a whole file into a byte array like this:File f = new File("somefile");
    int size = (int) f.length();
    byte[] contents = new byte[size];
    DataInputStream in = new DataInputStream(
                              new BufferedInputStream(new FileInputStream(f)));
    in.readFully(contents);
    in.close();Note that you need to add in the proper exception handling code. You could also use RandomAccessFile instead of the DataInputStream.
    Writing a byte array to a file is easier; just construct the FileOutputStream, call write on it with the byte array, and close the stream.

  • Filling empty java array in C method

    Hi everyone,
    I'm passing to a C method an empty byte array from the Java Side. I want the C method to fill the Java byte array and return it at the end of the method to the java side.
    in the Java side, I have my byte array :
    byte[] myArray = null;
    then I'm passing the array to the C method as
    myMethod(myArray)
    in the C method I'M trying to access the array as follow :
    myMethod(jbyteArray myArray)
    jbyte* tab = *env)->GetByteArrayElements(env, myArray, 0);
    I'm getting an error at runtime. Can somebody help me with that issue please ? Thanks
    Sebastien

    You are not passing a byte array, you are passing null.
    If you want to pass a byte array you first have to create it using the new operator:
    byte[] myArray = new byte[theSizeOfTheArray];
    myMethod(myArray);If you want the JNI code to create the array, that is fine also, but in that case the native method would probably have to return the array instead of void.

  • Problem in reading/writing byte array in Access database! PLEASE HELP!!

    Hi,
    I want to store a signature, which is in form of a byte array, in OLE Object field in MS Access database. I want then to retrieve this signature and verify it. The problem is that the retrieved byte array is not identical to the stored (original) one, and therefore, verifying the signature fails! Any help would be much appreciated as I can't proceed in my project without solving this problem. Here is the code to do the above mentioned functionality:
    //This part stores the signature (VT) in the table TTPTrans
    try
    { con = connect();
    ps = con.prepareStatement("UPDATE TTPTrans SET VT = ?, SigVT = ? WHERE TransID = ?");
    ps.setBinaryStream(1, new ByteArrayInputStream(vt), vt.length);
    ps.setBinaryStream(2, new ByteArrayInputStream(sigvt), sigvt.length);
    ps.setString(3, tID);
    ps.executeUpdate();
    ps.close();
    con.close();
    catch (Exception e)
    {  System.err.println(e.getMessage());
    e.printStackTrace();
    //This part retrive the signature from the table in the byte array o1:
    ResultSet result;
    byte[] o1 = null;
    byte[] o2 = null;
    try
    { con = connect();
    Statement statement = con.createStatement();
    result = statement.executeQuery("SELECT VT, SigVT" +
    " FROM TTPTrans" +
    " WHERE TransID = " + "'" +
    transID + "'");
    while (result.next()) {
    o1 = result.getBytes("VT");
    o2 = result.getBytes("SigVT");
    statement.close();
    con.close();
    catch(Exception e)
    { System.err.println(e.getMessage());
    e.printStackTrace();
    }

    In the following code, I use a ASN1SDSSSignature class, which is a subclass that I created from the Siganture class, to create and verify an SDSS signature. The ASN1SDSSSignature has two ASN1Integer class variables:
    signcryption = token.getSigncryption();
    sig.initVerify(ttpCert);
    sig.update(receivedVT);
    boolean verified = sig.verify(receivedSigVT);
    if(!verified)
    System.err.println("TTP signatire on received token invalid. ");
    notify()
    return;
    Where receivedVT and receivedSigVT are the byte arrays retrieved from th database. The following exception is thrown when I run the application:
    ASN1 type mismatch!
    Expected: codec.asn1.ASN1Integer
    In: ASN1SDSSSignature
    At index 0
    Got tag: 4 and Class: 0
    I hope this would clarify the situation and thanks in advance for any comments you may post.

  • Is there a null value that I can put into a byte array?

    I have a byte[] that I'm trying to make smaller, at the moment, in order to do so, i'm writing it byte-by-byte to another byte[] called temp. Both are set to the same size, because I don't know exactly what the initial array will compress to.
    For example, my method will write a single byte that will tell the decompressor to carry out the next instruction 5 times (eg aaaaa = 5a), but after the instruction, I want to set the 4 a's afterwards to an empty value so that I can then iterate through temp, finding out how long to make the output byte[] by counting how many null's there are.
    Eclipse is telling me null is not possible to use, I was just wondering if there is an equivalent I can use?

    That's an idea!
    The only thing is then when I come to iterate through the byte array to write it to my output array, it throws up an error that I'm trying to compare a byte to a byte[]:
              int next = 0;
              byte[] n = new byte[0];
              for (int i = 0; i < temp.length; i++) {
                   if (temp[i] != n) {
                        output[next] = temp;
                        next++;
              return output;

  • Converting an integer to a byte array?

    I have a checksum calculation and i stor it into an int. but when i saved to my test.dat file this number showd up as 05 in hex, which is only 1 byte out of 4 that is displayed. I have been looking around and playin and stuff but havent found anything helpful.
    checksum(4 bytes) : 2126934821
    // Stream access
    FileInputStream fischar;
    FileOutputStream outchar;
    // CS byte array
    byte [] orgCS = new byte[4];
    //byte [] bnewCS = new byte[4];
    int newCS;
    public void writecss() {
    System.out.print( "New checksum(" + 4 + " bytes) : "+newCS+"\n" );
    try{
    // writing original checksum and new checksum into a .dat file spaced with a zero
    outchar = new FileOutputStream( fcs );
    outchar.write(orgCS); // byte array being written
    outchar.write(0);
    outchar.write(0);
    outchar.write(newCS); // Int being written
    outchar.close();
    System.exit(0);
    }catch(IOException ioe){
    // Print IO error
    System.out.print( ioe );
    System.exit(0);
    the output is so
    FD6E 945E 0000 F3 : .n.^...
    you can see where the 2 zero bytes act like a spacer, and you see the integer being cut off for some reason. o_O can you help me out?

    Not sure if this help you?
         * Writes the specified byte to this output stream. The general
         * contract for <code>write</code> is that one byte is written
         * to the output stream. The byte to be written is the eight
         * low-order bits of the argument <code>b</code>. The 24
         * high-order bits of <code>b</code> are ignored.
         * <p>
         * Subclasses of <code>OutputStream</code> must provide an
         * implementation for this method.
         * @param      b   the <code>byte</code>.
         * @exception  IOException  if an I/O error occurs. In particular,
         *             an <code>IOException</code> may be thrown if the
         *             output stream has been closed.
        public void write(int b) throws IOException
         * Writes <code>b.length</code> bytes from the specified byte array
         * to this output stream. The general contract for <code>write(b)</code>
         * is that it should have exactly the same effect as the call
         * <code>write(b, 0, b.length)</code>.
         * @param      b   the data.
         * @exception  IOException  if an I/O error occurs.
         * @see        java.io.OutputStream#write(byte[], int, int)
        public void write(byte b[]) throws IOException Extract from OutputStream API

  • Byte Array Copy

    Hello,
    I have a problem that I have to write code to address the issue of modem disconnections while copying data. The problem is that I have to programmactially dial modems and copy programs to a remote windows based system. The issue is that I sometimes get disconnected from the remote site and loose my copy progress. I want to be able to be able to break apart an executable into chunks and copy those chunks to the remote harddrive and if I get disconnect, I will re dial the connection and pick up where I left off so that I dont loose the time that I spent already copying the file.
    I am currently using this method for copying the executables across the dial up connection but need to modify it and to be honest I dont know how. I know I should stuff the executable into some sort of byte array, get the length of that array, and copy each byte array element to the harddrive; loop through the array until the copy is complete. If disconnection or "semaphore timeout" exception is thrown, redial the connection, read the bytes that are already written on the remote locations harddrive, compare the bytes to what is stored locally, and copy those bytes until complete.
    Here is the method that I am using. I understand that I could use NIO to do the copy and it would be faster but I dont want to have to make major changes. I have attempted to search google for answers but only can find methods like this. Which is basically what I have...
        public static boolean uploadPackage(String src,String dst) {
            try {
                InputStream in = new FileInputStream(src);
                OutputStream out = new FileOutputStream(dst);
                // Transfer bytes from in to out
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    System.out.println("WRITING BUFFER " + len + " " + in.read(buf));
                    out.write(buf, 0, len);
                in.close();
                out.close();
                return true;
            } catch (IOException e) {
                System.out.println("IOEXCEPTION " + e);
                return false;
        }

    Dukes are worthless.
    Do you have a question? I didn't see one.
    Why do you feel the need to put a bunch of byte arrays to disk? The file itself is ultimately a byte array. Why not just store a file that says what the last byte successfully transferred was. Probably it should also indicate the last file modification date, so you can see if the file has changed out from under you between transfers. Then you can just reload the file and resend the bits you need.
    For that matter, there must be a system that can transfer files in bits. I used to do this with uuencode and split on shell script. I wouldn't be surprised if rsync or something like it has support for something like this.

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

  • Trying to send multiple types in a byte array -- questions?

    Hi,
    I have a question which I would really appreciate any help on.
    I am trying to send a byte array, that contains multiple types using a UDP app. and then receive it on the other end.
    So far I have been able to do this using the following code. Please note that I create a new String, Float or Double object to be able to correctly send and receive. Here is the code:
    //this is on the client side...
    String mymessage ="Here is your stuff from your client" ;
    int nbr = 22; Double nbr2 = new Double(1232.11223);
    Float nbr3 = new Float(8098098.809808);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(mymessage);
    oos.writeInt(nbr);
    oos.writeObject(nbr2);
    oos.writeObject(nbr3);
    oos.close();
    byte[] buffer = baos.toByteArray();
    socket.send(packet);
    //this is on the server side...
    byte [] buffer = new byte [5000];
    String mymessage = null; int nbr = 0; Double nbr2 = null;
    Float nbr3 = null;
    mymessage = (String)ois.readObject();
    nbr = ois.readInt();
    nbr2 = (Double) ois.readObject();
    nbr3 = (Float) ois.readObject();
    My main question here is that I have to create a new Float and Double object to be able to send and receive this byte array correctly. However, I would like to be able to have to only create 1object, stuff it with the String, int, Float and Double, send it and then correctly receive it on the other end.
    So I tried creating another class, and then creating an obj of this class and stuffing it with the 4 types:
    public class O_struct{
    //the indiv. objects to be sent...
    public String mymessage; public int nbr; public Double nbr2;
    public Float nbr3;
    //construct...
    public O_struct(String mymessage_c, int nbr_c, double nbr2_c, float nbr3_c){
    my_message = my_message_c;
    nbr = nbr_c;
    nbr2 = new Double(nbr2_c);
    nbr3 = new Float(nbr3_c);
    Then in main, using this new class:
    in main():
    O_struct some_obj_client = new O_struct("Here is your stuff from your client", 22, 1232.1234, 890980980.798);
    oos.writeObject(some_obj_client);
    oos.close();
    send code....according to UDP
    However on the receiving side, I am not sure how to be able to correctly retrieve the 4 types. Before I was explicitely creating those objects for sending, then I was casting them again on the receiving side to retrieve then and it does work.
    But if I create a O_struct object and cast it as I did before with the indiv objects on the receiving end, I can't get the correct retrievals.
    My code, on the server side:
    O_struct some_obj_server = new O_struct(null, null, null. null);
    some_obj_server = (O_struct)ois.readObject();
    My main goal is to be able to send 4 types in a byte array, but the way I have written this code, I have to create a Float and Double obj to be able to send and receive correctly. I would rather not have to directly create these objects, but instead be able to stuff all 4 types into a byte array and then send it and correctly be able to retrieve all the info on the receiver's side.
    I might be making this more complicated than needed, but this was the only way I could figure out how to do this and any help will be greatly appreciated.
    If there an easier way to do I certainly will appreciate that advise as well.
    Thanks.

    public class O_struct implements Serializable {
    // writing
    ObjectOutputStream oos = ...;
    O_struct struct = ...;
    oos.writeObject(struct);
    // reading
    ObjectInputStream ois = ...;
    O_struct struct = (O_struct)ois.readObject();
    I will be sending 1000s of these byte arrays, and I'm sure having to create a new Double or Float on both ends will hinder this.
    I am worried that having to create new objs every time it is sending a byte array will affect my application.
    That's the wrong way to approach this. You're talking about adding complexity to your code and fuglifying it because you think it might improve performance. But you don't know if it will, or by how much, or even if it needs to be improved.
    Personally, I'd guess that the I/O will have a much bigger affect on performance than object creation (which, contrary to popular belief, is generally quite fast now: http://www-128.ibm.com/developerworks/java/library/j-jtp01274.html)
    If you think object creation is going to be a problem, then before you go and cock up your real code to work around it, create some tests that measure how fast it is one way vs. the other. Then only use the cock-up if the normal, easier to write and maintain way is too slow AND the cock-up is significantly faster.

  • Ideas on transforming a byte array?

    I'm writing a program to compress files - I read it in, transform it and then write it out again. I'm just having a little confusion with the transforming.
    I'm keeping it as basic as possible and just starting with finding and replacing repeating bytes with an instruction of how many times the following byte is repeated. ie a a a a a = 5 a _ _ _
    In order to do this I create a temporary array to write to (initialised to the same size as the input) and then check through for repetitions. If something is repeated more than twice (3+), then a marker byte is put in (I wanted to have specific ones for however many times the byte is repeated - within reason - which is the switch statement below), the next byte is the byte to be repeated and then I want to jump forward to the next different byte.
    I then go through the temp array count the repetitions, create a new smaller byte array and write temp[] to output[] ignoring the bytes that are repeated.
    This is what I have so far, but it doesn't quite do what I want:
    public class Transformer {
         byte[] input;
         byte[] temp;
         byte[] output;
         byte rep;
         public Transformer() {
         public byte[] transform(byte[] in) {
              input = in;
              temp = new byte[in.length];
              output = new byte[count(input, temp)];
              output = compress(temp, output);
              return output;
         private int count(byte[] from, byte[] to) {
              int k = 0; // total bytes copied so far
              byte markerByte = (byte) 0xE1;
              for (int i = 0, j = 0; i < from.length; i = j) {
                   for (j = i+1; j < from.length && from[j] == from[i] && j-i < 128; j++);
                   if (j-i >= 3) {
                        to[k++] = markerByte;
                        to[k++] = (byte) (j-i);
                        to[k++] = from[j-1];
                   } else {
                        to[k] = from[k];
                        k = i+1;
              return k;
            // (the following method isn't finished)
         private byte[] compress(byte[] from, byte[] to) {
              for (int i = 0; i < from.length; i++) {
                   if (from[i] == (byte) 0xE1) {
                        System.out.println("repeat");
                   System.out.println(from);
              return to;
         private byte getRepeatByte(int numberOfRepeats) {
              byte instruction;
              switch (numberOfRepeats) {
              case 1: instruction = (byte) 0xE1; break;
              case 2: instruction = (byte) 0xE2; break;
              case 3: instruction = (byte) 0xE3; break;
              case 4: instruction = (byte) 0xE4; break;
              case 5: instruction = (byte) 0xE5; break;
              case 6: instruction = (byte) 0xE6; break;
              case 7: instruction = (byte) 0xE7; break;
              case 8: instruction = (byte) 0xE8; break;
              case 9: instruction = (byte) 0xE9; break;
              case 10: instruction = (byte) 0xEA; break;
              case 11: instruction = (byte) 0xEB; break;
              case 12: instruction = (byte) 0xEC; break;
              case 13: instruction = (byte) 0xED; break;
              case 14: instruction = (byte) 0xEE; break;
              case 15: instruction = (byte) 0xEF; break;
              default: instruction = (byte) 0xE0; break;
              return instruction;
    At the moment I'm using a marker byte in the transform() but I want to be using the switch statement to work out the right byte to put in first.
    Does anyone have any advice on if I'm doing this in a ridiculous way or if my methods won't work.. As I haven't written a decompressor yet, it's pretty hard to test!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    baftos - thank you for your advice, i will try that and see how it goes.
    Jos - it is your method and thank you very much for it! It's part of an ongoing project of mine, which is turning out to be more challenging than i originally thought - when i posted on the other forum your loop did perfectly what I was trying to do at the time. I need all the advice i can get and hence post on multiple forums.

  • How to add 16 bit message sequential number to the byte array

    hi
    iam trying to implement socket programming over UDP. Iam writing for the server side now.I need to send an image file from server to a client via a gateway so basically ive to do hand-shaking with the gateway first and then ive to send image data in a sequence of small messages with a payload of 1 KB.The data message should also include a header of 16 bit sequential number and a bit to indicate end of file.
    Iam able to complete registration process(Iam not sure yet).I dnt know how to include sequential number and a bit to indicate end of file.
    I would like to have your valuable ideas about how to proceed further
    package udp;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class Sender  {
        protected BufferedReader in = null;
        protected FileInputStream image=null;
        protected static boolean end_of_file=true;
    /** pass arguments hostname,port,filename
    * @param args
    * @throws IOException
       public static void main(String[] args) throws IOException{
            DatagramSocket socket = new DatagramSocket(Integer.parseInt(args[1]));
            boolean more_messages = true;
              String str1=null;
                * gateway registration
                try{
                     //send string to emulator
                    String str="%%%GatewayRegistration SENDER test delay 10 drop 0 dupl 0 bandwidth 1000000";
                    byte[] buff=str.getBytes();
                    InetAddress emulator_address = InetAddress.getByName(args[0]);
                    DatagramPacket packet = new DatagramPacket(buff, buff.length,emulator_address,Integer.parseInt(args[0]));
                    socket.send(packet);
                        // figure out response
                    byte[] buf = new byte[1024];
                    DatagramPacket recpack=new DatagramPacket(buf,buf.length);
                    socket.receive(recpack);
                   // socket.setSoTimeout(10000);
                    String str2=str1.valueOf(new String(recpack.getData()));
                    if(socket.equals(null))
                         System.out.println("no acknowledgement from the emulator");
                        socket.close();
                    else if(str2=="%%%GatewayConfirmation")
                    //     String str1=null;
                         System.out.println("rec message"+str2);
                    else
                         System.out.println("not a valid message from emulator");
                         socket.close();
                catch (IOException e) {
                    e.printStackTrace();
                      end_of_file = false;
         /**create a packet with a payload of 1     KB and header of 16 bit sequential number and a bit to indicate end of file
      while(end_of_file!=false)
          String ack="y";
          String seqnum=
           File file = new File(args[2]);                               
                    InputStream is = new FileInputStream(file);                 
            socket.close();
      private byte[] byteArray(InputStream in) throws IOException {
             byte[] readBytes = new byte[1024]; // make a byte array with a length equal to the number of bytes in the stream
          try{
             in.read(readBytes);  // dump all the bytes in the stream into the array
            catch(IOException e)
                 e.printStackTrace();
            return readBytes;
      

    HI Rolf.k.
    Thank you for the small program it was helpfull.
    You got right about that proberly there  will be conflict with some spurios data, I can already detect that when writing the data to a spreadsheet file.
    I writes the data in such a way, that in each line there will be a date, a timestamp, a tab and a timestamp at the end. That means two columns.
    When i set given samplerate up, that controls the rate of the data outflow from the device, (1,56 Hz - 200 Hz),   the data file that i write to , looks unorderet.
     i get more than one timestamp and severel datavalues in every line and so on down the spreadsheet file.
    Now the question is: Could it be that the function that writes the data to the file,  can't handle the speed of the dataflow in such a way that the time stamp cant follow with the data flowspeed. so i'm trying to set the timestamp to be  with fractions of the seconds by adding the unit (<digit>) in the timestamp icon but its not working. Meaby when i take the fractions off a second within the timestamp i can get every timestamp with its right data value. Am i in deeb water or what do You mean!??
    AAttached Pics part of program and a logfile over data written to file
    regards
    Zamzam
    HFZ
    Attachments:
    DataFlowWR.JPG ‏159 KB
    Datalogfile.JPG ‏386 KB

  • How do i covert an image in J2ME into an byte array ?

    Can anyone help to show me the way to convert an image into a byte array ?
    Thanks early reply appreciated.

    Hi! I�m developing an application to be installed in two devices. My problem is that i want to send an image: I can receive it with createImage(InputStream ip), but how can i send it with OutputStream? it needs a byte array (method write), how can i convert an image into a byte array?is there any other solution? like send it as a string...
    Thanks

  • How to find the last element of a byte array

    Dear all,
    I have a byte array with a max lenght of 1024*50 bytes. In that array I store the bytes read from a file. How can I find where the array ends (i.e. which is the last valid element of the byte array)?
    Thank you for your help.
    Best Regards,
    JIM

    I want to send files over TCP connection using BufferedOutputStreams and BufferedInputStreams. The first side (e.g. the client) sends a file (e.g mp3 file or jpeg image) to the server using the code
      public void sendFile(Socket s, String FileName) throws Exception
              BufferedOutputStream out = new BufferedOutputStream(s.getOutputStream());  
              BufferedInputStream in = new BufferedInputStream(new FileInputStream(FileName));
              int len = 0;
              while ( (len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
              in.close();
              out.flush();
            }(The client does not close the BufferedOutputStream out because other files will be sent afterwards)
    Then, the server receives the file using the code:
            public void receiveFile(Socket s, String FileName) throws Exception
              OutputStream out = new BufferedOutputStream(new FileOutputStream(FileName)); 
              InputStream in = new BufferedInputStream(s.getInputStream());
              int len = 0;
              while ( (len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
                break;
              out.flush();
              out.close();
            }(likewise the InputStream in is not closed for the same reasons).
    In order the server to receive the file and stop reading the BufferedInputStream, I will have to make some modifications to this part of the code,
    while ( (len = in.read(buffer)) > 0)so as to know when the whole file has been received.
    Thus, even if I send the length of each file, I will not be able to read it. Could you please recommend me a solution?

Maybe you are looking for

  • How to catch accounting Document Number in SE37 for  BAPI_ACC_DOCUMENT_POST

    HI Frds, My ReQ is i have to post Customer Invoice from Legacy to ECC through PI interface. So i am using one BAPI , ' BAPI_ACC_DOCUMENT_POST''. I had customized this BAPI by adding 2 fields (1.zstatus, 2.zsaprefno) as i have to send the status(1. Su

  • How to use checkbox in reports

    Hi, I am stuck a little here.I have given some selection-options, few parameters on screen and two checkboxes. How will i know which one is clicked.I will be glad if someone can provide me small snippet .

  • Time Based publishing on taxonomy

    Hi there, we have built a news application where everyone can post it's own news items. Location of the user is a personal folder created by using a userhome filter. The folder has time based publishing activated, the lifetime can be entered in the e

  • Using idvd themes in imovie and photshop?

    hi, i would like to use idvd themes for the cover art of a dvd and sounds for imovie clips. therefore, i wanted to know if and how it's possible to find the image-file of an idvd theme so that i can import it into photoshop, as well if and how i can

  • Love the Bundle (PSE8/PE8), but I HATE THE AUTO-ANALYZER

    Hello everyone; I'm a big fan of the Adobe Bundel's (PSE & PE), I have been using them for over 3 years now, I started with PSE4/PE2, then PSE6/PE4 and now PSE8/PE8. I'm also a very avid user of the Organizer Yes I do, Call me Crazy, but I do like it