Extend a byte array dynamically

Is it possible to dynamically extend a byte[] by consecutively adding content to it, just like e.g. extending a String with the += operation:String myString = [[some String data here]];
myString += [[some more String data to be added to myString here]]; and what is the most efficient way to do this? Thanks for any help.

Hi Laszlo,
thanks for answering. I need that behaviour for the following: I have a compressed binary file which I would like to decompress and store the decompressed contents in a byte[]. Since the decompressed contents will be definitely larger (but I do not initially know by how much), I cannot ascertain the size of the array. I wish I could add decompressed data as long as it is available to it...

Similar Messages

  • Creating a byte Array dynamically.Urgent Help needed.

    Hi there,
    I need to create a byte Array with the values
    derived from the array and then am passing this byte array
    to a method.
    Example :
    public static void main(String[] args) throws IOException {
    char chars[] = {'a','j','a','y'};
    byte[] b = {
    (byte) chars[0],(byte) chars[1],(byte) chars[2],(byte) chars[3],
    //** Send name to a server.
    sendRequest(b);
    This is all right.
    But here I know the size of the character array chars.
    If it had more than 4 characters or less than 4,
    is there a way to create the byte array dynamically based on the values in the character array?
    Please can some one help me with creating a byte array on the fly?
    Has anyone understood my question please?
    A response is much much appreciated.

    The actual problem is this.
    The byte array already has some fixed values to it
    and i need to append the values of the character array
    to this byte array
    ie
    char chars[] = {'a','j','a','y'};
    byte b[] = {
    // Predefined values
    (byte) 0x01, (byte) 0x7E, (byte)0x03
    // I have to add the values from the array here
    (byte) chars[0], (byte) chars[1]....
    How can I add these values.? The size of the character array
    can vary

  • Creating a byte Array dynamically.An Urgent Request.

    Hi there,
    I need to create a byte Array with the values
    derived from the array and then am passing this byte array
    to a method.
    Example :
    public static void main(String[] args) throws IOException {
    char chars[] = {'a','j','a','y'};
    byte[] b = {
    (byte) chars[0],(byte) chars[1],(byte) chars[2],(byte) chars[3],
    //** Send name to a server.
    sendRequest(b);
    This is all right.
    But here I know the size of the character array chars.
    If it had more than 4 characters or less than 4,
    is there a way to create the byte array dynamically based on the values in the character array?
    Please can some one help me with creating a byte array on the fly?
    Has anyone understood my question please?

    Well, if you have the byte array already, you're probably going to have to either make the original array large enough to hold whatever you would put into it or create a new array when you know what you are going to add.
    This seems pretty simple, so maybe I'm missing the point. But...
    char chars[] = { ... };
    byte bytes[] = new byte[<some other size> + chars.length];
    for (int i = 0; i < chars.length; i++)
    bytes[i + <offset>] = (byte)chars;
    If you can't effectively figure out a static size for this array and you have to copy contents, look at System.arrayCopy() to possibly improve performance of the copy.

  • Bit permutation inside a byte array

    Hi everyone,
    I'm trying to implement DES algorithm, i want to permute specified bits inside an 8byte array.
    I tought about extract every bits from the byte array inside a 64 byte array and then do the permutation.
    But i don't see how to put these bits back into an 8byte array to return the result of encryption/decryption.
    This is what i've done so far (inspired by sources i found on the internet) :
    // extends 8 byte array into a 64 byte array
    public static byte[] extendsByteArray(byte[] bytes) {
    byte[] tab = bytes;
    short len = (short)(desBlockSize * (short)8);
    byte[] bits = new byte[len];
    short i,j;
    for (i = (short)(desBlockSize - (short)1); i >=0; i--) {
    for (j = (short)0; j < desBlockSize; j++)
    bits[--len] = (byte) ((tab[i] >> j) & 0x01);
    return bits;
    // 64 byte array to 8 byte array
    public static byte[] transformByteArray(byte[] bits){
    byte[] tab = bits;
    byte[] bytes = new byte[desBlockSize];
    short i,j = (short)0;
    for ( i = (short)0; i < (short)8; i++){
    bytes[i] = (byte)((bits[j] * (short)2^7) + (bits[j+(short)1] * (short)2^6)+
                   (bits[j+(short)2] * (short)2^5) + (bits[j+(short)3] * (short)2^4)
                   + (bits[j+(short)4] * (short)2^3) + (bits[j+(short)5] * (short)2^2)
                   + (bits[j+(short)6] * (short)2) + (bits[j+(short)7]));
    j +=(short)7;
    return bits;
    This implementation doesn't seems to work, do u have some ideas why it doesn't work or is there an easier solution to permute bits as i'm stuck with this fo the moment.
    Thanks in advance for your answers,
    Julien

    If you are using JavaCard please do not use multiplications as you used in your code. Integer multiplications are very slow in any platform that does not implement them in hardware, and the virtual machine that runs in JavaCards usually does not do any optimizations or Just-In-Time compiling - simply interprets the codes. Memory and CPU power are at a premium in Java Cards. Even if your Java Card has a hardware multiplier, usually it is reserved for RSA operations - it is not available for general use for Java programs.
    Instead of using x * 2 raised to the sixth power, use x << 6. It is faster and generates fewer bytecodes.

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

  • Display byte array image or ole object in Section through dynamic code?

    To Start I am a Complete Newbe to Crystal Reports. I have taken over a project originally written in VS2003 asp.net using SQL Server 2005 and older version of Crytal Reports. I have moved project to VS2010 and Cryatal Reports 10 still using SQL Server 2005. Have multiple reports (14 to be exact) that display data currently being pulled from database suing a dataset, each report has from 4 to 14 Sections. I have modified database table with two new fields. Field1 contains string data with full path to a scanned document (pdf or jpeg). Field2 holds a byte array of the actual image of the scanned document. I have tested the database and it does infact contain the byte array and can display the image via VB.net code. I can make the report display the scanned image using ole object.
    Now my real question: I need to add a new Section and it should display either the byte array of the scanned image or the actual scanned image (pdf or jpeg) . How can I have it do either of these options via code dynamicly while application is running?

    First; only CRVS2010 is supported on VS2010. You can download CRVS2010 from here;
    SAP Crystal Reports, developer version for Microsoft Visual Studio: Updates & Runtime Downloads
    Developer Help files are here:
    Report Application Server .NET API Guide http://help.sap.com/businessobject/product_guides/sapCRVS2010/en/xi4_rassdk_net_api_en.zip
    Report Application Server .NET SDK Developer Guide http://help.sap.com/businessobject/product_guides/sapCRVS2010/en/xi4_rassdk_net_dg_en.zip
    SAP Crystal Reports .NET API Guide http://help.sap.com/businessobject/product_guides/sapCRVS2010/en/crnet_api_2010_en.zip
    SAP Crystal Reports .NET SDK Developer Guide http://help.sap.com/businessobject/product_guides/sapCRVS2010/en/crnet_dg_2010_en.zip
    To add the images, you have a number of options re. how to. You even have two SDKs that y ou can use (RAS and CR).
    Perhaps the best place to start is with KB [1296803 - How to add an image to a report using the Crystal Reports .NET InProc RAS SDK|http://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/oss_notes_boj/sdn_oss_boj_bi/sap(bD1lbiZjPTAwMQ==)/bc/bsp/spn/scn_bosap/notes%7B6163636573733d36393736354636443646363436353344333933393338323636393736354637333631373036453646373436353733354636453735364436323635373233443330333033303331333233393336333833303333%7D.do]. The KB describes how to add images to a report using the InProc RAS SDK, but also references other KBs that use CR SDK.
    Also, don't forget to use the search box in the top right corner of this web page.
    Ludek
    Follow us on Twitter http://twitter.com/SAPCRNetSup
    Got Enhancement ideas? Try the [SAP Idea Place|https://ideas.sap.com/community/products_and_solutions/crystalreports]

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

  • Playing a wav file (byte array) using JMF

    Hi,
    I want to play a wav file in form of a byte array using JMF. I have 2 classes, MyDataSource and MyPullBufferStream. MyDataSource class is inherited from PullStreamDataSource, and MyPullBufferStream is derived from PullBufferStream. When I run the following piece of code, I got an error saying "EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x7c9108b2, pid=3800, tid=1111". Any idea what might be the problem? Thanks.
    File file = new File(filename);
    byte[] data = FileUtils.readFileToByteArray(file);
    MyDataSource ds = new MyDataSource(data);
    ds.connect();
    try
        player = Manager.createPlayer(ds);
    catch (NoPlayerException e)
        e.printStackTrace();
    if (player != null)
         this.filename = filename;
         JMFrame jmframe = new JMFrame(player, filename);
        desktop.add(jmframe);
    import java.io.IOException;
    import javax.media.Time;
    import javax.media.protocol.PullBufferDataSource;
    import javax.media.protocol.PullBufferStream;
    public class MyDataSource extends PullBufferDataSource
        protected Object[] controls = new Object[0];
        protected boolean started = false;
        protected String contentType = "raw";
        protected boolean connected = false;
        protected Time duration = DURATION_UNKNOWN;
        protected PullBufferStream[] streams = null;
        protected PullBufferStream stream = null;
        protected final byte[] data;
        public MyDataSource(final byte[] data)
            this.data = data;
        public String getContentType()
            if (!connected)
                System.err.println("Error: DataSource not connected");
                return null;
            return contentType;
        public void connect() throws IOException
            if (connected)
                return;
            stream = new MyPullBufferStream(data);
            streams = new MyPullBufferStream[1];
            streams[0] = this.stream;
            connected = true;
        public void disconnect()
            try
                if (started)
                    stop();
            catch (IOException e)
            connected = false;
        public void start() throws IOException
            // we need to throw error if connect() has not been called
            if (!connected)
                throw new java.lang.Error(
                        "DataSource must be connected before it can be started");
            if (started)
                return;
            started = true;
        public void stop() throws IOException
            if (!connected || !started)
                return;
            started = false;
        public Object[] getControls()
            return controls;
        public Object getControl(String controlType)
            try
                Class cls = Class.forName(controlType);
                Object cs[] = getControls();
                for (int i = 0; i < cs.length; i++)
                    if (cls.isInstance(cs))
    return cs[i];
    return null;
    catch (Exception e)
    // no such controlType or such control
    return null;
    public Time getDuration()
    return duration;
    public PullBufferStream[] getStreams()
    if (streams == null)
    streams = new MyPullBufferStream[1];
    stream = streams[0] = new MyPullBufferStream(data);
    return streams;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import javax.media.Buffer;
    import javax.media.Control;
    import javax.media.Format;
    import javax.media.format.AudioFormat;
    import javax.media.protocol.ContentDescriptor;
    import javax.media.protocol.PullBufferStream;
    public class MyPullBufferStream implements PullBufferStream
    private static final int BLOCK_SIZE = 500;
    protected final ContentDescriptor cd = new ContentDescriptor(ContentDescriptor.RAW);
    protected AudioFormat audioFormat = new AudioFormat(AudioFormat.GSM_MS, 8000.0, 8, 1,
    Format.NOT_SPECIFIED, AudioFormat.SIGNED, 8, Format.NOT_SPECIFIED,
    Format.byteArray);
    private int seqNo = 0;
    private final byte[] data;
    private final ByteArrayInputStream bais;
    protected Control[] controls = new Control[0];
    public MyPullBufferStream(final byte[] data)
    this.data = data;
    bais = new ByteArrayInputStream(data);
    public Format getFormat()
    return audioFormat;
    public void read(Buffer buffer) throws IOException
    synchronized (this)
    Object outdata = buffer.getData();
    if (outdata == null || !(outdata.getClass() == Format.byteArray)
    || ((byte[]) outdata).length < BLOCK_SIZE)
    outdata = new byte[BLOCK_SIZE];
    buffer.setData(outdata);
    byte[] data = (byte[])buffer.getData();
    int bytes = bais.read(data);
    buffer.setData(data);
    buffer.setFormat(audioFormat);
    buffer.setTimeStamp(System.currentTimeMillis());
    buffer.setSequenceNumber(seqNo);
    buffer.setLength(BLOCK_SIZE);
    buffer.setFlags(0);
    buffer.setHeader(null);
    seqNo++;
    public boolean willReadBlock()
    return bais.available() > 0;
    public boolean endOfStream()
    return willReadBlock();
    public ContentDescriptor getContentDescriptor()
    return cd;
    public long getContentLength()
    return (long)data.length;
    public Object getControl(String controlType)
    try
    Class cls = Class.forName(controlType);
    Object cs[] = getControls();
    for (int i = 0; i < cs.length; i++)
    if (cls.isInstance(cs[i]))
    return cs[i];
    return null;
    catch (Exception e)
    // no such controlType or such control
    return null;
    public Object[] getControls()
    return controls;

    Here's some additional information. After making the following changes to MyPullBufferStream class, I can play a wav file with gsm-ms encoding with one issue: the wav file is played many times faster.
    protected AudioFormat audioFormat = new AudioFormat(AudioFormat.GSM, 8000.0, 8, 1,
                Format.NOT_SPECIFIED, AudioFormat.SIGNED, 8, Format.NOT_SPECIFIED,
                Format.byteArray);
    // put the entire byte array into the buffer in one shot instead of
    // giving a portion of it multiple times
    public void read(Buffer buffer) throws IOException
            synchronized (this)
                Object outdata = buffer.getData();
                if (outdata == null || !(outdata.getClass() == Format.byteArray)
                        || ((byte[]) outdata).length < BLOCK_SIZE)
                    outdata = new byte[BLOCK_SIZE];
                    buffer.setData(outdata);
                buffer.setLength(this.data.length);
                buffer.setOffset(0);
                buffer.setFormat(audioFormat);
                buffer.setData(this.data);
                seqNo++;
        }

  • Byte array convert to image works fine for a peiod of time, Then error

    Hi all
    I'm on a program of reading incoming image set which comes as byte arrays through socket and convert them back to images using the method.
    javax.microedition.lcdui.Image.createImage();This works perfect for some time.
    But after 1 minute of running it gives an error
    java.lang.OutOfMemoryError: Java heap space
            at java.awt.image.BufferedImage.getRGB(Unknown Source)
            at com.sun.kvem.midp.GraphicsBridge.loadImage(Unknown Source)
            at com.sun.kvem.midp.GraphicsBridge.createImageFromData(Unknown Source)
            at sun.reflect.GeneratedMethodAccessor14.invoke(Unknown Source)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
            at java.lang.reflect.Method.invoke(Unknown Source)
            at com.sun.kvem.sublime.MethodExecution.process(Unknown Source)
            at com.sun.kvem.sublime.SublimeExecutor.processRequest(Unknown Source)
            at com.sun.kvem.sublime.SublimeExecutor.run(Unknown Source)My J2ME client code
    public class ChangeImage extends Thread
        private SocketConnection sock = null;
        private Image img = null;
        private CanvasKey canvas = null;
        private InputStream in = null;
        public ChangeImage(SocketConnection sock, Canvas canvas) throws IOException
            this.sock = sock;
            this.canvas = (CanvasKey) canvas;
            in = sock.openInputStream();
        public void run()
            super.run();
            short length;
            while (true)
                DataInputStream din = null;
                try
                    din = new DataInputStream(in);
                    length = din.readShort();     // to determine next data packet size
                    byte[] arr = new byte[length];  // next data packet store here
                    din.readFully(arr);  //read image
                    img = Image.createImage(arr, 0, arr.length);
                    canvas.setImage(img);
                    ChangeImage.sleep(50);
                catch (Exception ex)
                    ex.printStackTrace();
    }When I comment following line no error prints.
    img = Image.createImage(arr, 0, arr.length);So the problem is not with socket program.
    What is this problem? Think old image isn't being flushed!!! in the method javax.microedition.lcdui.Image.createImage();Please help me.

    Forgot to Mention i'm using Windows 8.1 - 32 GB Ram - i7-3970x - 2 SSd's in raid 0 for C Drive/ Storage drive is three ( 2 tb HDD in a raid 0 ) / Pictures Folder defaults to the Storage Drive not the Application drive .

  • Display byte array of jpeg  in jsp

    I have a byte array of jpeg image in my jsp. Now I want to display it in my image. I tried but i could not see the image but a red mark image is comming on the screeen
    Please help me out. I deadly help need ASAP. Thanks in advance.
    this is how i tried
    response.setContentType("image/jpeg");
    ServletOutputStream os = response.getOutputStream();
    // i get byte array from loDocumentDVO.getFileContents():
    byte[] fileContent = loDocumentDVO.getFileContents();
    os.write(fileContent);
    os.flush();

    Thank you for your sharp words.
    I have now compiled the ImageServlet I have adapted slightly from http://balusc.xs4all.nl/srv/dev-jep-img.html
    I am trying to run it with
    <html>
    <body>
    <img src="image?file=plan.jpg" alt="Plan" />
    </body>
    </html>
    but all that is displayed is the word Plan.
    My servlet has been compiled and put into webapps\test\classes\example directory.
    My web.xml contains
    <servlet>
    <servlet-name>ImageServlet</servlet-name>
    <servlet-class>example.ImageServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>ImageServlet</servlet-name>
    <url-pattern>/image/*</url-pattern>
    </servlet-mapping>
    The servlet code is
    package example;
    import java.io.*;
    import java.net.URLConnection;
    import javax.servlet.*;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class ImageServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
              throws ServletException, IOException {
            String imageFilePath = getServletContext().getRealPath("/WEB-INF/images");
            // Get file name from request.
            String imageFileName = request.getParameter("file");
         System.out.println("Path: "+imageFilePath+" Name: "+imageFileName);
            // Check if file name is supplied to the request.
            if (imageFileName != null) {
                // Strip "../" and "..\" (avoid directory sniffing by hackers!).
                imageFileName = imageFileName.replaceAll("\\.+(\\\\|/)", "");
            } else {
                return;
            // Prepare file object.
            File imageFile = new File(imageFilePath, imageFileName);
            // Check if file actually exists in filesystem.
            if (!imageFile.exists()) {
                return;
            // Get content type by filename.
            String contentType = URLConnection.guessContentTypeFromName(imageFileName);
            // Check if file is actually an image (avoid download of other files by hackers!).
            // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
            if (contentType == null || !contentType.startsWith("image")) {
                return;
            // Prepare streams.
            BufferedInputStream input = null;
            BufferedOutputStream output = null;
            try {
                // Open image file.
                input = new BufferedInputStream(new FileInputStream(imageFile));
                int contentLength = input.available();
                // Init servlet response.
                response.reset();
                response.setContentLength(contentLength);
                response.setContentType(contentType);
                response.setHeader(
                    "Content-disposition", "inline; filename=\"" + imageFileName + "\"");
                output = new BufferedOutputStream(response.getOutputStream());
                // Write file contents to response.
                while (contentLength-- > 0) {
                    output.write(input.read());
                // Finalize task.
                output.flush();
            } catch (IOException e) {
                // Something went wrong?
                e.printStackTrace();
            } finally {
                // Gently close streams.
                if (input != null) {
                    try {
                        input.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        // This is a serious error. Do more than just printing a trace.
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        // This is a serious error. Do more than just printing a trace.
    }The servlet isn't being called - nothing is output to my server log file. Changing the name of my servlet doesn't change the result.
    I can't see why the servlet isn't being called.
    I have built another simple servlet that does work so I know my server is OK.
    Any suggestions?
    Thanks,
    David

  • Method to create Player directly from the mp3 bytes array

    I was checking JMF and didn't find any method to play a mp3 informing its byte array
    Wouldn't it be an interesting method ? Ok, URL is much easier, but I am talking about ID3 files that has sequences of mp3 chuncks in the same file... Anyone knows a way to build a Player from mp3' array of bytes ???

    sergio_abreu wrote:
    Err, Sorry but I desagree.I expected as much
    It seems you didn't understand my question well.Quite possibly
    I think the form I wrote was confusing:
    In +"Anyone knows a way to build a Player from mp3' array of bytes ???+"
    I meant: Anyone knows a way to create a Player or MediaPlayer CLASS from DYNAMIC mp3' array of bytes ???That's even less coherent, to be honest
    Have you seen the structure of an ID3 music file (album) ? It's a collection of mp3 chuncks in only one file.ID3 is simply metadata about a work. It is not "chunks of MP3"
    I have already designed a ID3 class (I called "ID3Info" ) in Java that extracts/shows (dump) all the mp3 from the ID3 file.ID3 isn't a file format. Nor can you extract an MP3 from it
    The thing I would need now is to have some methods in Manager Class from which I could choose which bytes of a generic file I want to load as an mp3 song, that's all.This makes zero sense. Like saying "I need a kettle which will turn furniture into weather"
    It would be nice if there were 2 new different methods:
    1) Player createRealizedPlayer( byte[] songBytes, String fileExtension);
    Arguments: the song byte array and the extension, ex. "mp3"And what would this method do? Where does the byte[] come from? What is in the file, that you also need in order to play the song? How is this - assuming it's possible - easier, better, than just playing the file?
    2) Player createRealizedPlayer( java.net.URL genericFileURL, int beginPosition, int endPosition, String fileExtension);
    Arguments: the URL of a file containing varios mp3 chuncks and the begin / end of the bytes to be loaded as a song and a String to describe the type of file ("mp3" for example)See above
    PS: If you find it interesting, I am willing to contribute to enrich even more the Java Media framework. If you think my ideas are not valid, I just ask someone to send me the jmf source code so that I can alter some classes for my tests only.Why do you need JMF source code? I don't think this magical upside-down-ness is going to enhance anything, to be honest

  • Truncate byte array of UTF-8 characters without corrupting the data?

    Hi all,
    I need to be able to determine if the byte array, which is truncated from the original byte array representing UTF-8 string, contains corrupted character. Knowing if the byte array contains corrupted character allows me to remove it from the truncated array.
    As in the sample code below, when truncate the string with 16 bytes it displays ok. However, truncate with 17 bytes, the last character is corrupted. Is there a way to check to see if the character is corrupted so that it can be removed from the truncated byte array?
    Thanks in advance,
    Phuong
    PS: The Japanese characters I chose it randomly from Unicode charts. I don't know their meaning so if it is offensive, please forgive me.
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.UnsupportedEncodingException;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.SwingUtilities;
    public class TestTruncateUTF8 extends JFrame
        private static final long serialVersionUID = 1L;
        private JTextArea textArea = new JTextArea(5,20);
        private JLabel japanese = new JLabel("Japanese: " + "\u65e5\u672c\u3041\u3086\u308c\u306e");
         * @param args
        public static void main(String[] args)
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run()
                    JFrame frame = new TestTruncateUTF8();
                    frame.setVisible(true);
        public TestTruncateUTF8()
            super("Test Truncated");
            JButton truncate17Button = new JButton("Truncate 17 bytes");
            truncate17Button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e)
                    truncates(17);
            JButton truncate16Button = new JButton("Truncate 16 bytes");
            truncate16Button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e)
                    truncates(16);
            JPanel panel1 = new JPanel();
            panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS));
            panel1.add(japanese);
            panel1.add(truncate16Button);
            panel1.add(truncate17Button);
            panel1.add(new JScrollPane(textArea));
            this.setLayout(new BorderLayout());
            this.add(panel1, BorderLayout.CENTER);
            this.pack();
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        private void truncates(int numOfBytesToTruncate)
            try
                byte[] bytes = japanese.getText().getBytes("UTF-8");
                byte[] newBytes = new byte[numOfBytesToTruncate];
                System.arraycopy(bytes, 0, newBytes, 0, numOfBytesToTruncate);
                TestTruncateUTF8.this.putTextInsideJTextArea(bytes, newBytes);
            catch (UnsupportedEncodingException e1)
                e1.printStackTrace();
        private void putTextInsideJTextArea(byte[] original, byte[] truncated)
            try
                textArea.append("\nOriginal String:  " + new String(original, "UTF-8"));
                textArea.append("\nTruncated String: " + new String(truncated, "UTF-8"));
                textArea.append("\n*****************************\n");
            catch (UnsupportedEncodingException e)
                e.printStackTrace();
    }

    Since the byte array is in UTF-8, you can easily examine whether it is corrupt or not by taking a look at the last 4 bytes (at most). That is because the bit distribution of each byte (1st, 2nd, 3rd, and 4th) in UTF-8 encoding is well defined in its spec.
    BTW, a Japanese Hiragana/Kanji character typically has 3 bytes in UTF-8, so truncating with neither 16 nor 17 bytes would produce correct truncation.
    HTH,
    Naoto

  • This byte array is not garbage collected?

    imageBytes[] does not seem to ever be garbage collected. I've pinpointed a SINGLE LINE that, when commented out, will prevent the memory leak. What could possibly be wrong with this line?
    Running this code results in a "OutOfMemoryError: Java heap space" after roughly a minute on my machine. I'm using JRE version 1.5.0_08.
    import javax.imageio.ImageIO;
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    // creates images to send to ImageConsumer
    public class ImageProducer {
         static BufferedImage bufferedImage;
         static Robot robo;
         static byte[] imageBytes;
         public static void main(String args[]) {
              try {
                   robo = new Robot();
              } catch(Exception e) {
                   e.printStackTrace();
              PipedOutputStream pos = new PipedOutputStream();
              new ImageConsumer(pos).start();
              bufferedImage = robo.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
              try {
                   ObjectOutputStream oostream = new ObjectOutputStream(pos);
                   ByteArrayOutputStream baos = new ByteArrayOutputStream();
                   ImageIO.write(bufferedImage, "JPG", baos);
                   baos.flush();
                   imageBytes = baos.toByteArray();
                   while (true) {
                        ImageIO.write(bufferedImage, "JPG", baos);
                        baos.flush();
                        // THIS SEEMS TO BE WHERE THE MEMORY LEAK OCCURS: imageBytes
                        // If you comment the following line out, there will be no
                        // memory leak. Why?  I ask that you help me solve this.
                        imageBytes = baos.toByteArray();
                        baos.reset();
                        oostream.writeObject(imageBytes);
                        pos.flush();
              } catch (Exception e) {
                   e.printStackTrace();
    // This thread reads the image data into bImg
    class ImageConsumer extends Thread {
         BufferedImage bImg;
         PipedInputStream pis;
         ImageConsumer(PipedOutputStream pos) {
              try {
                   pis = new PipedInputStream(pos);
              } catch (IOException e) { e.printStackTrace();}
         public void run() {
              try {
                   ObjectInputStream oinstream = new ObjectInputStream(pis);
                   while (true) {
                        byte[] imageBytes = (byte[])oinstream.readObject();
                        ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);
                        bImg = ImageIO.read(bais);
              } catch (Exception e) {e.printStackTrace();}
    }

    while (true) {
         ImageIO.write(bufferedImage, "JPG", baos);
         baos.flush();
         // THIS SEEMS TO BE WHERE THE MEMORY LEAK OCCURS: imageBytes
         // If you comment the following line out, there will be no
         // memory leak. Why? I ask that you help me solve this.
         imageBytes = baos.toByteArray();
         baos.reset();
         oostream.writeObject(imageBytes);
         pos.flush();
    }I have only briefly gone through the code, but why are you flushing it right before calling that line. Won't the byte array returned always be empty right after flushing the stream?

  • How to get the byte[] size dynamically from the StreamMessage object

    Hi all,
    Using JMS, I am receiving the FDF file as StreamMessage from the queue and attaching it to the PDF file which is present in the local system.
    For that, I have written the code as follows:
    {color:#0000ff} Message msg = jmsTemplate.receive();
    if(msg !=null && msg instanceof StreamMessage)
    StreamMessage message = (StreamMessage) msg;{color}
    {color:#ff6600}//hardcoded the byte array size value
    {color}{color:#0000ff} byte[] bytes = new byte[{color:#ff0000}856{color}];
    System.out.println("read msg="+message.readBytes(bytes));{color}
    {color:#0000ff}PdfReader pdfreader = new PdfReader("D:\\Managing_Workflows_No_Comment.pdf");
    PdfStamper stamp = new PdfStamper(pdfreader, new FileOutputStream("D:\\12345.pdf"));
    FdfReader fdfreader = new FdfReader(bytes);
    stamp.addComments(fdfreader);
    {color} {color:#0000ff} stamp.close();
    {color}{color:#000000}The above code is working fine except with the hardcoded of {color:#ff0000}byte array{color}{color:#ff0000} size value{color} which is given in {color:#ff0000}RED{color} in color.
    Can anybody know, {color:#000000}*how to get the byte[] size dynamically from the StreamMessage*{color} object ?
    Any help would be highly beneficial for me !!!!
    Thanks and Regards,
    Ganesh Kumar{color}

    When you create your stream message you could add an property to your message, something like streamSize that would contain the number of bytes in your stream message. Then you could get this property from the message before declaring your array.
    Tom

  • Read Video data from buffer or byte array

    Hi guys,
    I've developed a tx/rx module, the tx read an mpg file and transfer it over network. rx has the data in a byte array, I also feed the byte array to a media buffer. Now my question is how to creat the player and feed the player to play the content of the buffer or byte array?
    I would really appreaciate if someone could help me please...
    Thanx
    I haven't and didn't want to use any of the RTP stuff...

    Hi, I tried PullBufferDataSource. What I am trying to do is : read a .wav file into a queue, then construct a datasource with this queue. The processor will be contructed to process the datasource, and a datasink to sink data to a file. I think if this workflow could work, it should work in network transmission.
    In fact the code works partially. The trick part is the read( Buffer ) method. If I try to use 'if' statement to see if Queue has empty or not, the datasink could not format the head part of output file correctly. If I didnot use 'if' statement, the program will terminate when exception occurs. The output file is all right.
    I did not understand what is going on.
    Note: the original file is a RAW data file without format info.
    Here is the code fragments. Hopefully we can work together to figure it out.
    Thanks.
    Jim
    * QueueDataSourceTester.java
    * Created on November 11, 2002, 10:29 AM
    package bonephone;
    import javax.media.*;
    import javax.media.control.*;
    import javax.media.protocol.*;
    import javax.media.datasink.*;
    import javax.media.format.AudioFormat;
    import java.util.LinkedList;
    import java.io.*;
    * @author wguo
    public class QueueDataSourceTester implements ControllerListener, DataSinkListener {
    protected LinkedList myQueue;
    /** Creates a new instance of QueueDataSourceTester */
    public QueueDataSourceTester() {
    myQueue = new LinkedList();
    public void testIt( ){
    // Read a file into a Queue
    FileInputStream inputStream = null;
    try{
    inputStream = new FileInputStream( "c:/media/phone.wav");
    catch( IOException ioe ){
    System.err.println( "Error on open media file." );
    try{
    byte data[] = new byte[1024];
    int n ;
    while( ( n = inputStream.read( data, 0, 1024 )) != -1 ){
    myQueue.addLast( data );
    data = new byte[1024];
    inputStream.close();
    catch( IOException ioe ){
    System.err.println( "Error on reading file." );
    System.out.println( "Queue Size: " + myQueue.size() );
    System.out.println( "myQueue = " + myQueue.size() );
    QueueDataSource dataSource = new QueueDataSource( myQueue );
    Processor p = null ;
    try{
    System.out.println( "Create processor for QueueDataSource ... " );
    p = Manager.createProcessor( dataSource );
    catch( Exception e ){
    System.err.println( "Cannot create a processor for the QueueDataSource. " );
    System.out.println( "\nProcessor is created." );
    p.addControllerListener( this );
    p.configure();
    if( !waitForState( p, p.Configured ) ) {
    System.err.println( "Failed to configure the processor." );
    System.out.println( "\nProcessor is configured") ;
    // p.setContentDescriptor( new ContentDescriptor( ContentDescriptor.RAW ) );
    p.setContentDescriptor( new ContentDescriptor( FileTypeDescriptor.WAVE ) );
    TrackControl tcs[] = p.getTrackControls();
    Format f[] = tcs[0].getSupportedFormats();
    if( f == null || f.length == 0 ){
    System.err.println( "The mux does not support the input format : "+ tcs[0].getFormat() );
    tcs[0].setFormat(
    new AudioFormat( AudioFormat.ULAW,
    8000,
    8,
    1,
    Format.NOT_SPECIFIED,
    AudioFormat.SIGNED,
    8,
    Format.NOT_SPECIFIED,
    Format.byteArray ) );
    //System.out.println( "Setting the track format to: " + f[4] );
    p.realize();
    if( !waitForState( p, p.Realized )){
    System.err.println( "Failed to realize the processor" );
    DataSink dsink;
    MediaLocator outML = new MediaLocator("file:/c:/media/queue.wav" );
    if( (dsink = createDataSink( p, outML )) == null ){
    System.err.println( "Failed to create a datasink for given " +
    "mediaLocator : " + outML );
    dsink.addDataSinkListener( this );
    System.out.println( "\nProcessor is realized" );
    try{
    p.start();
    dsink.start();
    catch( IOException ioe ){
    System.err.println( "IO error during processing." );
    waitForFileDone();
    try{
    dsink.close();
    catch( Exception e ){
    p.removeControllerListener( this );
    System.err.println( "... done processing." );
    DataSink createDataSink( Processor p, MediaLocator outML ){
    DataSource ds ;
    if( ( ds = p.getDataOutput() ) == null ) {
    System.err.println( "Something is really wrong: the processor does" +
    " not have an output DataSource. " );
    return null;
    System.out.println( "DataOutput: " + ds.getContentType() );
    DataSink dsink;
    try{
    System.out.println( "- create DataSink for : " + outML );
    dsink = Manager.createDataSink( ds, outML );
    dsink.open();
    catch( Exception e ){
    System.err.println( "Cannot create the DataSink: " + e );
    return null;
    return dsink;
    Object waitSync = new Object();
    boolean stateTransitionOK = true;
    boolean waitForState( Processor p, int state ){
    synchronized( waitSync ){
    try{
    while( p.getState() < state && stateTransitionOK )
    waitSync.wait();
    catch( Exception e ){
    return stateTransitionOK;
    public void controllerUpdate(javax.media.ControllerEvent controllerEvent) {
    if( controllerEvent instanceof ConfigureCompleteEvent ||
    controllerEvent instanceof RealizeCompleteEvent ||
    controllerEvent instanceof PrefetchCompleteEvent ){
    synchronized( waitSync ){
    stateTransitionOK = true;
    waitSync.notifyAll();
    } else if( controllerEvent instanceof ResourceUnavailableEvent ){
    synchronized( waitSync ){
    stateTransitionOK = false;
    waitSync.notifyAll( );
    public static void main( String args[] ){
    QueueDataSourceTester tester = new QueueDataSourceTester();
    tester.testIt();
    Object waitFileSync = new Object();
    boolean fileDone = false;
    boolean fileSuccess = true;
    boolean waitForFileDone(){
    synchronized( waitFileSync ){
    try{
    waitFileSync.wait( 5000 );
    catch( Exception e ){
    System.err.println( "Error on waiting file to be done" );
    return fileSuccess;
    public void dataSinkUpdate(javax.media.datasink.DataSinkEvent dataSinkEvent) {
    if( dataSinkEvent instanceof EndOfStreamEvent ){
    synchronized( waitFileSync ){
    fileDone = true;
    waitFileSync.notifyAll();
    else if ( dataSinkEvent instanceof DataSinkErrorEvent ){
    synchronized( waitFileSync ){
    fileDone = true;
    fileSuccess = false;
    waitFileSync.notifyAll();
    // Inner Class
    * A datasource that will read Media data from Queue.
    * Inside queue individual RAW data packats are stored.
    * @author wguo
    public class QueueDataSource extends PullBufferDataSource{
    protected QueueSourceStream streams[];
    /** Creates a new instance of QueueDataSource */
    public QueueDataSource( LinkedList source ) {
    printDebug( "QueueDataSource: QueueDataSource( LinkedList) " );
    streams = new QueueSourceStream[1];
    streams[0] = new QueueSourceStream( source );
    public void connect() throws java.io.IOException {
    printDebug( "QueueDataSource: connect() " );
    public void disconnect() {
    printDebug( "QueueDataSource: disconnect()" );
    public String getContentType() {
    return ContentDescriptor.RAW;
    public Object getControl(String str) {
    printDebug( "QueueDataSource: getControl(String) " );
    return null;
    public Object[] getControls() {
    printDebug( "QueueDataSource: getControls() " );
    return new Object[0];
    public javax.media.Time getDuration() {
    return DURATION_UNKNOWN;
    public javax.media.protocol.PullBufferStream[] getStreams() {
    printDebug( "QueueDataSource: getStreams() " );
    return streams;
    public void start() throws java.io.IOException {
    printDebug( "QueueDataSource:start()" );
    public void stop() throws java.io.IOException {
    printDebug( "QueueDataSource: stop() " );
    private void printDebug( String methodInfo ){
    System.out.println( methodInfo + " is called" );
    // Inner Class
    public class QueueSourceStream implements PullBufferStream{
    LinkedList sourceQueue;
    AudioFormat audioFormat;
    boolean ended = false;
    /** Creates a new instance of QueueSourceStream */
    public QueueSourceStream( LinkedList sourceQueue ) {
    printDebug( "QueueSourceStream: QueueSourceStream( LinkedList )" );
    this.sourceQueue = sourceQueue;
    audioFormat = new AudioFormat(
    AudioFormat.ULAW,
    8000,
    8,
    1,
    Format.NOT_SPECIFIED,
    AudioFormat.SIGNED,
    8,
    Format.NOT_SPECIFIED,
    Format.byteArray);
    public boolean endOfStream() {
    printDebug( "QueueSourceStream: endOfStream()" );
    return ended;
    public javax.media.protocol.ContentDescriptor getContentDescriptor() {
    printDebug( "QueueSourceStream: getContentDescriptor()" );
    return new ContentDescriptor( ContentDescriptor.RAW) ;
    public long getContentLength() {
    printDebug( "QueueSourceStream:getContentLength()" );
    return 0;
    public Object getControl(String str) {
    printDebug( "QueueSourceStream:getControl( String) " );
    return null;
    public Object[] getControls() {
    printDebug( "QueueSourceStream:getControls()" );
    return new Object[0];
    public javax.media.Format getFormat() {
    printDebug( "QueueSourceStream:getFormat()" );
    return audioFormat;
    public void read(javax.media.Buffer buffer) throws java.io.IOException {
    buffer.setData( (byte[])sourceQueue.removeFirst() );
    buffer.setOffset( 0 );
    buffer.setLength( 1024 );
    buffer.setFormat( audioFormat );
    printDebug( "QueueSourceStream: read( Buffer ) " );
    else {
    buffer.setEOM( true );
    buffer.setOffset( 0 );
    buffer.setLength( 0 );
    ended = true;
    System.out.println( "Done reading byte array" );
    return;
    public boolean willReadBlock() {
    printDebug( "QueueSourceStream: willReadBlock()" );
    if( myQueue.isEmpty() )
    return true;
    else
    return false;
    private void printDebug( String methodInfo ){
    System.out.println( methodInfo + " is called. " );

Maybe you are looking for