Writing byte array to JspWriter

Hi,
I'm pretty new to JSPs / Servlets and I have what may be a silly question. In side of a JSP scriptlet, I call an external library which returns me a byte[] containing a sequence characters in a single byte encoding (utf-8, I think). Essentially, I want to write this single byte text to the implicit out object, but that doesn't work as the underlying Writer (as I understand things) is expecting utf16.
Here's some psuedocode showing what I'd like to do, but can't quite:
<%
byte[] myBytes = myModule.methodReturnsUTF8Bytes( );
out.write(myBytes);
%>
So, what can I do? Thanks in advance.
-ts1971

ts1971 wrote:
<%
byte[] myBytes = myModule.methodReturnsUTF8Bytes( );
String myString = new String(myBytes, "UTF-8");
out.write(myString);
%>Just set the response encoding. More about characters and bytes in Java/JSP/Servlet: [http://balusc.blogspot.com/2009/05/unicode-how-to-get-characters-right.html].
Oh, take care with memory usage. The above code is memory hogging.

Similar Messages

  • 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.

  • 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.

  • 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.

  • 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.

  • 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;

  • 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" />

  • 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 to open a byte array of pdf into acrobat reader dynamically..

    hi,
    my java program is connecting to a url and downloading various file(.pdf,.xml format) into hard-disk. now the requirement is if user select "Preview" button, then file is downloaded and opened with appropriate application(acrobat reader for .pdf file) but not saved anywhere in hard-disk ...
    any idea, any hint any help is welcomed..
    thanks in advance..

    hi friends,
    i got the solution. i am using one external api of adobe acrobat, through which i am able to stream pdf document in form of byte array into acrobat viewer,without writing data in any file.
    so my work is done.. :)

  • 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

  • Trouble writing pixel array back to gif file

    Hi everyone. I am in the middle of constructing a steganography api for a final year group project. I have taken out the pixels into an array from a gif file. I am having trouble writing it back to a gif file. Here is my code:
    import javaSteg.stegoLibrary.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import Acme.*;
    import Acme.JPM.Encoders.*;
    public class Gif extends Canvas{
         public void encodeGif(byte[] imageData){
              //create toolkit obarrayPointerect
              Toolkit t = Toolkit.getDefaultToolkit();
              MediaTracker tracker = new MediaTracker(this);
              //decode specified Gif cover
              Image img = t.createImage(imageData);      
              tracker.addImage(img,0);
              try{
                   tracker.waitForAll();
              catch(InterruptedException e){
              System.out.println("Tracker interrupted.");
              //retrive picture from image
              int[] pix = new int[img.getWidth(this) * img.getHeight(this)];
              PixelGrabber pg = new PixelGrabber(img, 0, 0, img.getWidth(this), img.getHeight(this), pix, 0, img.getWidth(this));
              try{ pg.grabPixels();
              } catch (InterruptedException ioe) {
                   System.err.println("Interrupted");
              if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
              System.err.println("image fetch aborted or errored");
              return;
              //put into byte array
              byte[] pixels = new byte[img.getWidth(this) * img.getHeight(this)];     
              for(int arrayPointer=0;arrayPointer<pix.length;arrayPointer++){
                   pixels[arrayPointer] = new Integer(pix[arrayPointer]).byteValue();
              //edit pixels not implemented yet
    //assign edited pixels to an image
              img = t.createImage(pixels);
              // Now encode the image using ACME free GIF encoder (www.acme.com)
              try{
                   FileOutputStream fos = new FileOutputStream("D:\\result.gif");
                   GifEncoder encoder = new GifEncoder(img, fos);
                   encoder.encode();
                   fos.close();
              }catch(IOException e) {
              System.out.println("FATAL IOException "+e);
    From this i get a single pixel in my output gif file. Is there a way of swapping out the edited pixels with the origonal pixels in the image file? or an alternative way to write back the complete file.
    Thanks a lot
    MickyT

    ive managed to solve it. For those who come across this thread and want to know the solution i needed to use MemoryImageSource with the pixels inorder to pass them to the createImage method :o)

  • Use byte array of PDF to display PDF in IE browser

    I get byte array of PDF as input argument. I need to use byte array to display PDF in IE browser. I am writing code in doGet method of Servlet to accomplish this. However, PDF never gets displayed. I see Acrobat starting, but original PDF never gets displayed in browser.
    I am using code below in doGet of Servlet:
    resp.setContentType("application/pdf");
    resp.setHeader("Expires", "0");
    resp.setHeader("Cache-Control","must-revalidate, post-check=0,
    pre-check=0");
    resp.setHeader("Pragma", "public");
    resp.setHeader("Pragma", "no-cache"); //HTTP 1.0
    resp.setDateHeader("Expires", 0); //prevents caching at the proxy
    server
    resp.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
    resp.setHeader("Cache-Control", "max-age=0");
    resp.setHeader("Content-disposition", "inline; filename=stuff.pdf");
    byte[] inBytes = getBytesOfPDF(...);
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    if(inBytes !=null){
    outStream.write(inBytes);
    outStream.flush();
    I added dummy name of PDF (stuff.pdf) for display, as I heard IE requires a file name with .pdf extension for display.
    But I had no luck with the code above.
    Any help with code will be appreciated.
    [email protected]

    Hi
    Am using the same code and i am able to get the PDF out.
              /* Finally writing it into a PDF */
                   response.setContentType("application/pdf");
                   /* filename could be any thing */
                   response.setHeader("Content-Disposition",
                             "attachment; filename=Report.pdf");
                   response.setContentLength(content.length);
                   response.getOutputStream().write(content);
                   response.getOutputStream().flush();
    But this also throws a error in the server :
    java.lang.IllegalStateException: getOutputStream() has already been called for this response
         at org.apache.catalina.connector.Response.getWriter(Response.java:606)
         at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:195)
         at org.springframework.web.servlet.view.freemarker.FreeMarkerView.processTemplate(FreeMarkerView.java:344)
         at org.springframework.web.servlet.view.freemarker.FreeMarkerView.doRender(FreeMarkerView.java:280)
         at org.springframework.web.servlet.view.freemarker.FreeMarkerView.renderMergedTemplateModel(FreeMarkerView.java:225)
         at org.springframework.web.servlet.view.AbstractTemplateView.renderMergedOutputModel(AbstractTemplateView.java:174)
         at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:239)
         at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1142)
         at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:879)
         at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:792)
         at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:476)
         at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:441)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
         at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:672)
         at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:463)
         at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:398)
         at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:301)
         at org.ca.ielts.presentationtier.servlet.AuthorisationAuthenticationFilter.doFilter(Unknown Source)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:868)
         at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:663)
         at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
         at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
         at java.lang.Thread.run(Thread.java:595)
    Any Clues how this has to be fixed.????

  • 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.

  • 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.

Maybe you are looking for

  • Printing Problem with Wipro Printer

    hi , i have developed the smartform which contain page format of size height DINA4 .when i am giving print in wipro dot printer it is printing in correct postion in first page but in next page it displaying below the postion what i am given .plz tell

  • BT Infinity available at my exchange, still can't ...

    OK I won't bore you all to much with the details of the quest to get an internet connection, but it basically goes like this. I moved address and when I tried to 'move' my BT Infinity service was told it was not available at my new address. I did a c

  • Something went wrong with running nokia express

    same problem in my mobile.

  • SAP in a Oracle server

    Is it possible to apply and use a SAP as a layer on a Oracle Database. Should the DBA have the knowledge on SAP to perform this... ?

  • Modifying Portal URL to use Fully Qualified Domain Name

    Hi, We have a portal that I can access now by using the URL 'invsrvr001:50000/irj/portal'. We would need the URL to use the fully qualified domain name such as 'invsrvr001.company.com:50000/irj/portal'. Towards that end we added the profile paramter