Save byte[] array to file

Hi,
I've read a .jpg picture off the hard disk and stored in a byte[] array. I've altered some of the bytes and want to save the file back to .jpg. Is there a method available in java which allows me to do this?
Thanks and regards,
Krt_Malta

FileOutputStream#write(byte[] array).

Similar Messages

  • Save byte array (image) to file with servlet

    Good day.
    I should must to save a png image to file.
    I have a byte array of the image.
    This work is in a servlet.
    How can I do it?
    Best regards.
    Stefano Errani

    Good day.
    I have a byte[] and then I have used
    FileOutputStream fos = new FileOutputStream(getServletContext().getRealPath("/public_html/mcfoto/foto1.png"));
    fos.write(bt, 0, bt.length); // byte[] bt
    fos.close();
    This on my web server that has public_html as root web directory.
    The server is in multi domain.
    In this mode I have an error.
    Then I have tryied to use
    FileOutputStream fos = new FileOutputStream("http://www.stefanoerrani.it/mcfoto/foto1.png");
    and
    FileOutputStream fos = new FileOutputStream(getServletContext().getRealPath("http://www.stefanoerrani.it/mcfoto/foto1.png"));
    In both ways I have obtained an error.
    At last I have tryied in my localhost (local machine) using
    FileOutputStream fos = new FileOutputStream(getServletContext().getRealPath("/mcfoto/foto1.png"));
    All run correclty.
    The Application Server is Tomcat with Apache HTTP Server.
    The first server (of www.stefanoerrani.it) has Linux as OS.
    My local server has Windows as OS.
    I should want, if it's possible, an help.
    Best regards.
    Stefano Errani

  • How to save Byte Array of raw data into JPEG image.

    Hello!
    I have a image and I stored its data as byte array as
    bimage = bitmap1.getRawData();
    now I have Byte[] bimage, I want to save it as .jpeg image.
    and show that image..............

    the short way is this:
    ImageIO.write(bimage, "jpeg", new File("image.jpg"));
    Where you use the original Image object... but it has to be a java.awt.image.RenderedImage (which a java.awt.image.BufferedImage is). So this method would come in handy.
         public static BufferedImage getBufferedImage(Image img) {
              // if the image is already a BufferedImage, cast and return it
              if((img instanceof BufferedImage) && background == null) {
                   return (BufferedImage)img;
              // otherwise, create a new BufferedImage and draw the original
              // image on it
              int w = img.getWidth(null);
              int h = img.getHeight(null);
              BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g2d = bi.createGraphics();
              g2d.drawImage(img, 0, 0, w, h, null);
              g2d.dispose();
              return bi;
         }If the byte array you have is raw image data, then you can look at the javax.imageio package and see what you can do with those classes.

  • Displaying byte array PDF file in Portal

    Hi,
    i need to display a PDF file. The PDF is stored in a byte array. This works fine when i run my code (see below) from the .jpf via the debugger/browser, but when i use it as a portlet, in the portal, it does not work ?
    Any help is much appreciated.
    Thanks
    Mark
    byte[] pdfDocument = docStore.getPDF();
    ServletOutputStream outPdf = response.getOutputStream();
    response.setContentType("application/pdf");
    outPdf.write(pdfDocument);
    outPdf.flush();
    outPdf.close();

    Mark,
    Note that the portal sets the content type (e.g, text/html) and encoding
    as the portal page starts rendering. In your case, the
    setContentType() would be useless since the servlet container won't let
    you change it. You can either use a popup browser window for the pdf as
    Kunal suggested, or use an iframe if you want to render the pdf inside
    the portlet window.
    Subbu
    Mark Gilleece wrote:
    Hi,
    i need to display a PDF file. The PDF is stored in a byte array. This works fine when i run my code (see below) from the .jpf via the debugger/browser, but when i use it as a portlet, in the portal, it does not work ?
    Any help is much appreciated.
    Thanks
    Mark
    byte[] pdfDocument = docStore.getPDF();
    ServletOutputStream outPdf = response.getOutputStream();
    response.setContentType("application/pdf");
    outPdf.write(pdfDocument);
    outPdf.flush();
    outPdf.close();

  • Save byte[] to a file

    Hi,
    I have a byte[] and I am trying to save it to a file.....such as a tar.gz or .zip file..... how would I do that?
    I have taken the byte[] and made a string, and then saved it ...but i think this would be different right?
    thanks.

    public static InputStream getInputStream(String tarFileName) throws Exception{
          if(tarFileName.substring(tarFileName.lastIndexOf(".") + 1, tarFileName.lastIndexOf(".") + 3).equalsIgnoreCase("gz")){
             System.out.println("Creating an GZIPInputStream for the file");
             return new GZIPInputStream(new FileInputStream(new File(tarFileName)));
          }else{
             System.out.println("Creating an InputStream for the file");
             return new FileInputStream(new File(tarFileName));
       public static void readTar(InputStream in, String untarDir) throws IOException{
          System.out.println("Reading TarInputStream... (using classes from http://www.trustice.com/java/tar/)");
          TarInputStream tin = new TarInputStream(in);
          TarEntry tarEntry = tin.getNextEntry();
          if(new File(untarDir).exists()){
               while (tarEntry != null){
                  File destPath = new File(untarDir + File.separatorChar + tarEntry.getName());
                  System.out.println("Processing " + destPath.getAbsoluteFile());
                  if(!tarEntry.isDirectory()){
                     FileOutputStream fout = new FileOutputStream(destPath);
                     tin.copyEntryContents(fout);
                     fout.close();
                  }else{
                     destPath.mkdir();
                  tarEntry = tin.getNextEntry();
               tin.close();
          }else{
             System.out.println("That destination directory doesn't exist! " + untarDir);
       }

  • Turn byte array into file

    hi,
    I got a byte array from a file and want to turn it into a file, so i can access it thru the operating system.
    byte[] lop = rs.getBytes("data");
    can anyone give any help, or a good tutorial to do this.

    Check out the API docs for the FileOutputStream class and pay special attention to its
    write(byte[]) method.
    kind regards,
    Jos

  • How to save Java byte Array in Oracle

    Hi All,
    I'm using Java and need to save byte Array in Database. Initially the column is varchar2 type. is it possible to save in this type or need to modify the column type to CLOB.
    please clarify me.
    thanks in advance.
    regards
    pavan.

    You might want to use a BLOB instead
    because CLOB & varchar2 are strings unless you encode your byte array
    CLOB & varchar2 datatypes won`t record 0x00 if you have any in your array
    it will be considered as the string terminator

  • Byte array to base64encoder problem, cannot encode a 7.7 MB file

    hey guys, so ive been trying to use the base64encoder to encode a bytearray which is then sent thru a webservice to the server to be decoded.
    and as the subject of this post suggests, i have been having problems encoding a big file,
    forexample i tried to upload/convert a 84KB image and it worked just fine... the trace of the string ended with a "==" which i believe means that the conversion is complete...
    but when i try to upload a 7.7MB image, it is, i guess, crashing... i dont see any "==" in the string... so i guess its not working... i was wondering if there is any any type of file size limit or soemthign for the encoding...
    the code i have is
    import flash.events.Event;
    import flash.net.FileFilter;
    import flash.net.FileReference;
    import flash.utils.ByteArray;
    import mx.collections.ArrayCollection;
    import mx.controls.Alert;
    import mx.rpc.events.FaultEvent;
    import mx.rpc.events.ResultEvent;
    import mx.utils.Base64Encoder;
    import services.images.ImageData;
    import services.images.Images;
    import services.images.ReturnMessage;
    // ActionScript file
        public var fileRef:FileReference = new FileReference();
        public var imgCollection:ArrayCollection = new ArrayCollection();
        public var imgService:Images = new Images();
        public var imageData:ImageData = new ImageData();
        public var returnMsg:ReturnMessage = new ReturnMessage();
        public function onBrowseButtonClicked(event:MouseEvent):void{
            var arr:Array = [];
            arr.push(new FileFilter("Images", ".gif;*.jepg;*.jpg;*.png"));
            fileRef.browse(arr);
            fileRef.addEventListener(Event.SELECT, fileRef_select);
            fileRef.addEventListener(Event.COMPLETE, fileRef_complete);
        public function fileRef_select(event:Event):void{
            fileRef.load();
        public function fileRef_complete(event:Event):void{
            img.source = fileRef.data;
            var fileByteArr:ByteArray = fileRef.data;
            var b64En:Base64Encoder = new Base64Encoder();
            b64En.encodeBytes(fileByteArr);                                                  //<----------------------------------------------------------
            var str:String = b64En.flush();                                                        //<----------------------------------------------------------
            trace(str.length);
            b64En.reset();
            trace("------------------------------------      " + str + "     -----------------------------");
            imageData.Base64EncodedImage = str;
            imageData.FileName = "nameofstring";
            imgService.UploadImage(imageData);
           imgService.addEventListener(FaultEvent.FAULT, servFault);
           imgService.addEventListener(ResultEvent.RESULT, imgServSuccess);
        public function imgServSuccess(event:ResultEvent):void{
            Alert.show("i am in the result");
            returnMsg = event.result as ReturnMessage;
            var resultStr:String = event.result as String;
            Alert.show(resultStr);
            if(returnMsg.ThereWasAnError){
                trace(returnMsg.ErrorMessages.getItemAt(0).toString());
        public function servFault(event:FaultEvent):void{
            Alert.show("2 " + event.fault.message);
            Alert.show("3 " + event.fault.faultCode);
    any help will be greatly appretiated!! thanks in advace!

    yeah i did actually... except i think i changed a LOT of code since i last posted this article...
    so i dont remember where this code is exactly... lol
    i have the following code now...
    hope this helps
    i use a a lot of webservices... so there is some of that code included in there aswell...
    * This file will do the file upload. It has been suggested to me multiple times, that using a queueing system for
    * file upload is not a good idea. Instead I declared a counter and used the final function to fire the next item
    * in the array. this also makes canceling a routine easier.
    import flash.events.Event;
    import flash.events.ProgressEvent;
    import flash.net.FileReference;
    import flash.net.FileReferenceList;
    import flash.utils.ByteArray;
    import mx.collections.ArrayCollection;
    import mx.controls.*;
    import mx.managers.*;
    import mx.rpc.events.FaultEvent;
    import mx.rpc.events.ResultEvent;
    import mx.utils.Base64Decoder;
    import mx.utils.Base64Encoder;
    import services.images.Images;
    import valueObjects.*;
        public var t:Number = 0;
        public var fileRef:FileReferenceList = new FileReferenceList();
        public var listCacheFiles:Array = new Array();
        [Bindable] public var fileListArr:Array = new Array();
        [Bindable] public var fileNames:ArrayCollection = new ArrayCollection();
        [Bindable] public var arrUploadFiles:Array = new Array();
        public var file:FileReference;
        public var _numCurrentUpload:Number = 0;
        public var imageData:valueObjects.ImageData;
        public var imageService:Images = new Images();
        public var saveImages:Images;
        public var returnMsg:ReturnMessage = new ReturnMessage();
        public var dataToSave:ImageData;
        public var myCounter:int = 0;
        public var numPerc:Number;
        /*vars to possible delete*/
        public var fileListx:ArrayCollection;
         * Initiates the browse, when files are selected the selectionHandler function is called
        public function initiateBrowse():void{
            var filter:Array = [];
            filter.push(new FileFilter("Images", ".gif;*.jepg;*.jpg;*.png"));
            fileRef.addEventListener(Event.SELECT, selectionHandler);
            fileRef.browse(filter);
         * selection handler takes the selected files and puts them in 2 different arrays
         * fileListArr contains all the file information like the image itself and the name and everything
         * fileNames contains the information essential to populate the datagrid in the cropper.mxml
        public function selectionHandler(event:Event):void{
            //trace("selection Handler ->>");
            fileRef.removeEventListener(Event.SELECT, selectionHandler);
            var numSelected:int = event.target.fileList.length;
            var fileList:Array = event.target.fileList;
            fileListx = new ArrayCollection();
            fileListx = event.target.fileList as ArrayCollection;
            //var oldListLength:Number = fileListArr.length;
            for each(var item:Object in fileList){
                fileListArr.push(item);
                fileNames.addItem({
                    num: fileNames.length + 1,
                    name: item.name,
                    size: formatFileSize(item.size),
                    status: "",
                    itemDetails: item
            var newListLength:Number = fileListArr.length;
            if(myCounter > 0)
                loopList(myCounter);
            else
                loopList(0);
         * this function starts one, new filereference for each files in the array
        public function loopList(value:int):void{
            //trace("looplist -->");
            if(value < fileListArr.length){
                _numCurrentUpload = value;       
                file = new FileReference();
                file = FileReference(fileListArr[value]);;
                file.addEventListener(Event.COMPLETE, loadImage);
                file.addEventListener(ProgressEvent.PROGRESS, fileProgress);
                file.load();
         * This function will convert the byte array into a string, and then it sends it to the server.
        public function loadImage(event:Event):void{
            trace("loadImage -->");
            file.removeEventListener(Event.COMPLETE, loadImage);
                myCounter += 1;
                var fileByteArr:ByteArray = event.target.data;
                var b64En:Base64Encoder = new Base64Encoder();
                b64En.encodeBytes(fileByteArr);
                var str:String = b64En.flush();
                imageData = new ImageData();
                imageData.Base64EncodedImage = str;
                imageData.FileName = event.target.name;
                trace("sending -->>  " + imageData.FileName);
                updateStatus("Sending to server");
                imageService.addEventListener(ResultEvent.RESULT, imgServSuccess);
                imageService.UploadImage(imageData);
                b64En.reset();
         * This function will decode the information recieved back from the server.
        public function imgServSuccess(event:ResultEvent):void{
            trace("imgServSuccess -->");
            imageService.removeEventListener(ResultEvent.RESULT, imgServSuccess);
            var returnedImageId:ArrayCollection = new ArrayCollection();
            returnMsg = event.result as ReturnMessage;
            var returnedData:Object = event.result.Images;
            var imgD:ImageData = new ImageData();
            if(returnMsg.ThereWasAnError){
                trace(returnMsg.ErrorMessages.getItemAt(0).toString());
            else{
                for each(var imgData:ImageData in returnedData){
                    var decoded:Base64Decoder = new Base64Decoder();
                    decoded.decode(imgData.Base64EncodedImage);
                    var byteArr:ByteArray = decoded.toByteArray();
                    //img.source = byteArr;
                dataToSave = new ImageData();
                dataToSave = returnedData[0];
                listCacheFiles.push(dataToSave);
                updateStatus("Item in Cache");
                //uploadDetails.visible = true;
                loopList(myCounter);
        public var win:itemDetails;
        public function itemClicking(event:Event):void{
            var fileName:String = event.currentTarget.dataProvider[0].name;
            for(var i:Number = 0; i < listCacheFiles.length; i++){
            //var temp:ImageData = event.target as ImageData;
            win = null;
            win = itemDetails(PopUpManager.createPopUp(this, itemDetails, true));
            win.title = "Enter Details";
            PopUpManager.centerPopUp(win);
            win["save"].addEventListener("click", popupClosed);
        public function popupClosed(event:Event):void{
            var returnedData:ImageData = new ImageData;
            returnedData = win.dataToSave;
            saveImgAndData(returnedData);
        public function saveImgAndData(data:ImageData):void{
            saveImages = new Images;
            saveImages.showBusyCursor = true;
            saveImages.addEventListener(ResultEvent.RESULT, savedSuccess);
            saveImages.addEventListener(FaultEvent.FAULT, faultFunc);
            saveImages.SaveUploadedImageInformation(data);
        public function faultFunc(event:FaultEvent):void{
            Alert.show(event.fault.message);
            Alert.show(event.fault.faultString);
        public function savedSuccess(event:ResultEvent):void{
            //trace("savedSuccess -->");
            var retMsg:Object = event.result.Images;
            //trace("saving -->> " + retMsg[0].FileName);
            updateStatus("Completed");
            //loopList(myCounter);
        private function formatFileSize(numSize:Number):String {
            var strReturn:String;
            numSize = Number(numSize / 1024);
            strReturn = String(numSize.toFixed(1) + " KB");
            if (numSize > 1024) {
                numSize = numSize / 1024;
                strReturn = String(numSize.toFixed(1) + " MB");
                if (numSize > 1024) {
                    numSize = numSize / 1024;
                    strReturn = String(numSize.toFixed(1) + " GB");
            return strReturn;
        public function removeFiles():void{
            var arrSelected:Array = displayFilesList.selectedIndices;
            if(arrSelected.length >= 1){
                for(var i:Number = 0; i < arrSelected.length; i++){
                    fileNames[Number(arrSelected[i])] = null;
                var idx:int = 1;
                for(var j:Number = 0; j < fileNames.length; j++){
                    if(fileNames[j] == null){
                        fileNames.removeItemAt(j);
                        j--;
                    }else{
                        fileNames[j].num = idx++;
                if(fileNames.length > 0)
                    displayFilesList.selectedIndex = 0;
                else
                    displayFilesList.selectedIndex = -1;
                _numCurrentUpload--;
                updateProgBar();
        private function updateStatus(status:String, index:Number = -1):void{
            index = _numCurrentUpload;
            fileNames[index].status = status;
            displayFilesList.invalidateList();
        public function fileProgress(event:ProgressEvent):void{
            //trace("fileProgress -->");
            var numPerc:Number = Math.round((Number(event.bytesLoaded) / Number(event.bytesTotal)) * 100);
            updateStatus("Uploading: " + numPerc.toString() + "%");
            updateProgBar(numPerc);
            var evt:ProgressEvent = new ProgressEvent("uploadProgress", false, false, event.bytesLoaded, event.bytesTotal);
            dispatchEvent(evt);
        public function updateProgBar(numPerc:Number = 0):void{
            //trace("updateProgBar -->");
            var strLabel:String = (_numCurrentUpload + 1) + "/" + fileNames.length;
            progBar.label = strLabel;
            progBar.setProgress(_numCurrentUpload + numPerc / 100, fileNames.length);
            progBar.validateNow();

  • How to create PNG file from byte array of RGB value?

    Hi
    Here is my problem.
    I have drawn some sketchs (through code in runtime) on canvas. I have grabbed the RGB information for the drwan image and converted to byte array.
    I have to pass this byte array to server and generate a png file and save.
    Please help.

    {color:#ff0000}Cross posted{color}
    http://forum.java.sun.com/thread.jspa?threadID=5218093
    {color:#000080}Cross posting is rude.
    db{color}

  • Main.vi creates 2D Arrays and I want to save the arrays in an microsoft Excel file(e.g engine_1)and in differnt worksheets(e.g. measure_1;measure_2;...)

    main.vi creates 2D Arrays and I want to save the arrays in an microsoft Excel file(e.g engine_1)and in differnt worksheets(e.g. measure_1;measure_2;...)
    The path(Grundpfad)for the excel file should be inserted in the main.vi.

    1. There's a shipping example called Write Table To XL.vi (Help>Find Examples>Communicating with External Applications>ActiveX>Excel) that you can use as a starting point.
    2. Buy the LabVIEW Report Generation Toolkit. Info can be found here.
    3. Search this forum for other examples of writing to Excel.

  • How do I read directly from file into byte array

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

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

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

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

  • How to save a value in a byte array, retrieve it and display it?

    Hi,
    I am doing a project for my data structures class that involves saving a value (given in String format) in a byte array (our 'memory'). Initially I just tried casting character by character into the byte array and casting back to char[] for retrieval (using .toString() to return what's supposed to be the original string), but this did not work. I tried the .getBytes() method, applying it to the string and then trying to recover it by placing the contents of the 'memory' in a byte array and applying toString(), but that didn't work either. I looked a bit and found this class, CharsetEncoder and CharsetDecoder. I tried to use these but when I try the compiler tells me I cannot instantiate CharsetDecoder because it is an abstract class. At this point I'm at a loss as to what I can do. Is there any way to place a string in a byte array and then recover the string in it's original format? For example, I might save a value in my particular class of "456". But when I try to recover the value from my 'memory' i.e. the byte array, it comes out like [gnue@hnju.... or something similar. I need it to output the original string ("456").
    Below is my code as it is right now, for the methods setValue and getValue.
    Thanks!
    public void setValue(String value) throws InvalidValueException {
         //… stores the given value in the memory area assigned to the variable
              if(this.type.isValidValue(value)){
                   bytes = value.getBytes();
                   int i,j,k;
                   int l=0;//might be wrong?
                   int ad=address-(address%4);
                   mem.readWord(ad);
                   reg=mem.getDataRegister();
                   if((address%4)+bytes.length-1<4){
                        for(i=address%4;i<address%4+bytes.length;i++)
                             reg.setByte(i, bytes[i]);
                        mem.setDataRegister(reg);
                        mem.writeWord(ad);
                   else if((address%4)+bytes.length-1>=4){
                        if(address%4!=0){
                             for(i=address%4;i<4;i++){
                                  reg.setByte(i, bytes);
                                  l++;
                             mem.setDataRegister(reg);
                             mem.writeWord(ad);
                             ad+=mem.WORDSIZE;
                        while(ad<address+bytes.length-(address+bytes.length)%4){
                             for(j=0;j<4;j++){
                                  reg.setByte(j, bytes[j+l]);
                                  l++;
                             mem.setDataRegister(reg);
                             mem.writeWord(ad);
                             ad+=mem.WORDSIZE;
                        if((address+bytes.length)%4!=0){
                             mem.readWord(ad);
                             reg=mem.getDataRegister();
                             for(k=0;k<(address+bytes.length)%4;k++){
                                  reg.setByte(k, bytes[k+l]);
                                  l++;
                             mem.setDataRegister(reg);
                             mem.writeWord(ad);
                   else
                        throw new InvalidValueException("The value passed is not valid.");
         /** Gets the current value of the variable.
         @return current value converted to String
         public String getValue() {
              //… returns the current value stored in the corresponding memory area
              //… value is converted to String
              bytes=new byte[this.getType().getSize()];
              int i,j,k;
              int l=0;//might be wrong?
              int ad=address-(address%4);
              mem.readWord(ad);
              reg=mem.getDataRegister();
              if((address%4)+bytes.length-1<4){
                   for(i=address%4;i<address%4+bytes.length;i++)
                        bytes[i] = reg.readByte(i);
              else if((address%4)+bytes.length-1>=4){
                   if(address%4!=0){
                        for(i=address%4;i<4;i++){
                             bytes[i] = reg.readByte(i);
                             l++;
                        ad+=mem.WORDSIZE;
                   mem.readWord(ad);
                   reg=mem.getDataRegister();
                   while(ad<address+bytes.length-(address+bytes.length)%4){
                        for(j=0;j<4;j++){
                             bytes[j+l] = reg.readByte(j);
                             l++;
                        ad+=mem.WORDSIZE;
                   if((address+bytes.length)%4!=0){
                        mem.readWord(ad);
                        reg=mem.getDataRegister();
                        for(k=0;k<(address+bytes.length)%4;k++){
                             bytes[k+l] = reg.readByte(k);
                             l++;
              return bytes.toString();

    You can certainly put it into a byte array and then construct a new String from that byte array. Just calling toString doesn't mean you'll automatically get a meaningful string out of it. Arrays do not override the toString method, so the use the one inherited from object.
    Look at String's constructors.

  • Using the jprogress bar for file byte array downloads

    I am currently using a byte array to send files back and forth between computers. To show a file is transferring i change the mouse to the hour glass but would like to use the jprogressbar.
    To send the file i read the file from one computer into a byte array, and then send it through an objectoutputstream. I am not sure how the file is sent or received though. What can i use to judge the length of time it takes to get one file from one computer to the other? In doing a debug, it looks like the oos sends the file to the other computer, and it is basically like an uploading process. is there a way for me to judge or tell how much of the file that is being uploaded is left?
    Thanks in advance

    If i know the file size how can i then check the progression? I would also like to use an progress bar on the upload of a file to the other computer, and for the download of the byte array to the other computer i could first give it the file size. if then what can i use to base my progression off of?
    i looked at this and it says i am not able to do it, but thought there might have been improvements in the jdk since then, and i might not be seeing them
    http://forum.java.sun.com/thread.jspa?threadID=357217&messageID=1490887
    Thanks

Maybe you are looking for

  • Client Copy error during client export / RX file is not getting generated

    Hi Experts, During the client export process of client copy in order to created two tranports requests(<SID>KT* and <SID>KX) for import we need to have the RT and RX files in data file folder and RT and RX in Co-file folder of usr\sap\trans. But I am

  • Commit session

    Hi I have some requirement such that i have to fill a table thru DBlink and number of records are too high... Is there any way i can Commit the session after regular intervals say after every 1 million recrds or so. Thanks in advance.

  • Cost center (KS02)

    Hi Experts, Iam trying to add new fields in cost center(ks02) using COOMKS01 enhancement(CMOD). My doubt is in ks02 there is BUKRS field.How can i get this bukrs value into my new tab? I could not find any structure to hold the CSKS data. Reward guar

  • Working With Image

    Hi, How to write a code by using keylistener to delete the key component in java

  • ITunes account; Change to email to mobileme?

    I have an iTunes account. I wanted to switch my email for the account to my new mobileme email address. iTunes will not let me change it to my @me address, stating that I may log into that account. Why is this? If I log into the other account, I wont