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

Similar Messages

  • Reading a JPEG as a byte array.

    Hello everyone.
    I am developing a project which involves using JPEG images with Java. I would like to use the java.awt.Image class but there's a snag:
    I am reading the file in as a byte array and then need to pass the bytes to an object to be displayed as an image. "why not just read it as a normal JPEG file in the first place?!" I hear you say. Yes, this would be easier but there is a good reason as to why I am reading as a byte array first and this cannot be worked around.
    If anyone has some suggestions I'd very much like to hear them.
    All the best,
    P.M.

    If all you're going to do is display the image, then you can use Toolkit#createImage(byte[] imagedata). That's about as direct as you can get. If you plan on manipulating the images in any way, though, then as above post says ByteArrayInputStream + ImageIO is the way to go.
    "why not just read it as a normal JPEG file in the first place?!" I hear you say. Yes, this would be easier but there is a good reason as to why I am reading as a byte array first and this cannot be worked around.Fun fact: For the ImageIO package, reading from the file is actually faster than reading from an InputStream that references the file's contents as a byte[] array. Specifically, the ImageInputStream implementation that wraps the file is faster then the one that wraps a generic InputStream.

  • Problem with string constructor when using byte array as parameter

    I am creating a string using constructor and passing byte array as parameter.This byte array i am getting from MessageDigest's digest() method,i.e. a hash value.
    The problem is when i iterate through byte array i can able to print all the values in byte array.But when i construct a string from that byte array and printing that string ,that is printing some unknown characters.
    I don't know whether i need to pass charsequence to the constructor and the type of charsequence.Can anybody help me?
    Thanks in advance

    Is there some problem today? I'm getting this sort of thing all over.
    I already told you and so did Kayaman. Don't. String is not a holder for binary data. You have to Base-64 encode it. If you don't you cannot reconstruct the original binary digest value, so putting it into a database is completely utterly and entirely pointless.
    Is that clear enough?

  • Problem with byte array arguments in webservice method call

    I am using JWSDP 1.5 to generate client stubs for a webservice hosted on a Windows 2000 platform.
    One of the methods of the webservice contains a byte array argument. When our application calls this method passing the contents of a TIFF file as the byte array, the method is failing. I have discovered that tthe reason for the failure is that the byte array in the SOAP message has been truncated and is missing its terminating tag.
    Is this a known problem in JWSDP 1.5? Is there a fix for it? Does JWSDP 1.6 resolve this problem?
    Any assistance will be much appreciated.
    Regards,
    Leo

    I'd like to add the the webservice being invoked by the generated client stubs is rpc/encoded.

  • Assigning value to a two-dimensional byte array - problem or not?

    I am facing a really strange issue.
    I have a 2D byte array of 10 rows and a byte array of some audio bytes:
    byte[][] buf = new byte[10][];
    byte[] a = ~ some bytes read from an audio streamWhen I assign like this:
    for (int i=0; i<10; i++) {
        a = ~read some audio bytes // this method properly returns a byte[]
        buf[i] = a;
    }the assignment is not working!!!
    If I use this:
    for (int i=0; i<10; i++) {
        a = ~read some audio bytes
        for (int j=0; j<a.length; j++) {
            buf[i][j] = a[j];
    }or this:
    for (int i=0; i<10; i++) {
        System.arraycopy(a, 0, buf, 0, a.length);
    }everything works fine, which is really odd!!
    I use this type of value assignment for the first time in byte arrays.
    However, I never had the same problem with integers, where the problem does not appear:int[] a = new int[] {1, 2, 3, 4, 5};
    int[][] b = new int[3][5];
    for (int i=0; i<3; i++) {
    b[i] = a;
    // This works fineAnybody has a clue about what's happening?
    Is it a Java issue or a programmers mistake?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Back again! I'm trying to track down the problem.
    Here is most of my actual code to get a better idea.
    private void test() {
         byte[][] buf1 = new byte[11][];
         byte[][] buf2 = new byte[11][];
         AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(audioFile);
         byte[] audioBytes = new byte[100];
         int serialNumber = 0;
         while (audioInputStream.read(audioBytes) != -1) {
              if (serialNumber == 10) {
                   serialNumber = 0; // breakpoint here for debugging
              // Fill buf1 -- working
              for (int i=0; i<audioBytes.length; i++) {
                   buf1[serialNumber] = audioBytes[i];
              // Fill buf2 -- not working
              buf2[serialNumber] = new byte[audioBytes.length];
              buf2[serialNumber] = audioBytes;
              serialNumber++;
    }I debugged the program, using a debug point after taking 10 "groups" of byte arrays (audioBytes) from the audio file.
    The result (as also indicated later by the audio output) is this:
    At the debug point the values of buf1's elements change in every loop, while buf2's remain unchanged, always having the initial value of audioBytes!
    It's really strange and annoying. These are the debugging results for the  [first|http://eevoskos.googlepages.com/loop1.jpg] ,  [second|http://eevoskos.googlepages.com/loop2.jpg]  and  [third|http://eevoskos.googlepages.com/loop3.jpg]  loop.
    I really can't see any mistake in the code.
    Could it be a Netbeans 6.1 bug or something?
    The problem appears both with jdk 5 or 6.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

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

  • How to get the encoding of a byte array (or ByteBuffer)?

    Hello;
    I have a byte array which may be encoded with any kind of encoding and I want to determine which encoding was used to encode this byte array. Does anyone know how to do this?
    Thanks in advance..

    Byte Arrays have NO encoding at all. When bytes are packed to characters, that is where encoding comes into picture. java.lang.String has enough methods to do that.
    [email protected]

  • Problem while encoding byte[] with RSA

    Hi all,
    I am trying to encode a byte array using RSA encoding. I use the following code (It tries to encode a byte array, "data", with the public key, "publicKey"):
    byte[] encryptData  = new byte[data.length];
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    ByteArrayInputStream inStream = new ByteArrayInputStream(data);
    CipherInputStream cipherStream = new CipherInputStream(inStream, cipher);
    cipherStream.read(encryptData);And all I get is a empty array: encryptData is full of zero!
    Does anyone have an idea about what I did wrong ?
    Thanks in advance

    ok...
    Indeed, my data length is far more than my key length. So you tell me that I should cut my data to have some chunks of smalled size (key length max), and use directly something Cipher ?
    EDIT: Oh, I just got it. I should cut the data into bits of KEY_SIZE minus 11 (for the minimum padding). I'm going to test that.
    EDIT 2: Ok, that's fine, you were right. My error was to use CipherInputStream on data which length was more than key size minus padding. Thank you very much for your answer.
    Edited by: Reeter on Mar 29, 2009 1:10 PM
    Edited by: Reeter on Mar 29, 2009 1:35 PM

  • Problem in using the install()'s byte array values?

    I tried to pass the values to the OwnerPIN object at the time of initialization. But when I try to install the applet I will get 6A80 error code . Can anybody tell me why I am getting this message. And if i use some different data values for pin.update() then I wont come across those error codes
    public static void install(byte[] bArray, short bOffset, byte bLength)     {          
              // GP-compliant JavaCard applet registration
              new SampleApp(bArray, (short) (bOffset), bLength);                    
         private SampleApp(byte[] bArray, short bOffset, byte bLength){
              pin = new OwnerPIN(PIN_TRY_LIMIT, MAX_PIN_SIZE);
              pin.update(bArray,bOffset, bLength);          
                    register();
    cm>  install -i a00000006203010c0601 -l -q C9#(1122331122331122) a00000006203010c06 a00000006203010c0601
    => 80 E6 0C 00 2E 09 A0 00 00 00 62 03 01 0C 06 0A    ..........b.....
        A0 00 00 00 62 03 01 0C 06 01 0A A0 00 00 00 62    ....b..........b
        03 01 0C 06 01 01 10 0A C9 08 11 22 33 11 22 33    ..........."3."3
        11 22 00 00
    ( 5411 usec)
    <= 6A 80

    GP 2.1.1, A.2 GlobalPlatform on a Java Card, Installation:
    Installation
    In Section 3.1 - The Method install of the Java Card� 2.1.1 Runtime Environment (JCRE) Specifications,
    the parameters passed to the method are defined to be initialization parameters from the contents of the incoming
    byte array parameter.
    In the definition of the install method of the Class Applet of the Java Card� 2.1.1 Application Programming
    Interface, the install parameters to be supplied must be in the format defined by the applet.
    This specification expands on this requirement and further defines the content of the install parameters. This
    expansion affects both the implementation of an OPEN and the behavior of a Java Card applet developed for a
    GlobalPlatform card. It does not affect the definition of the install method of the Class Applet of the Java
    Card� 2.1.1 Application Programming Interface specification.
    The install parameters shall identify the following data, present in the INSTALL [for install] command (see
    Section 9.5.2.3.2 - Data Field for INSTALL [for install]):
    � The instance AID,
    � The Application Privileges and,
    � The Application Specific Parameters.
    [While the APDU command contains install parameters representing TLV coded system and application specific parameters, the
    application only requires knowledge of the Application Specific Parameters i.e. only LV of the TLV coded structure �C9� are
    present as parameters.]
    The OPEN is responsible for ensuring that the parameters (bArray, bOffset and bLength) contain the
    following information:
    The array, bArray, shall contain the following consecutive LV coded data:
    _� Length of the instance AID,_
    _� The instance AID,_
    _� Length of the Application Privileges,_
    _� The Application Privileges,_
    _� Length of the Application Specific Parameters and,_
    _� The Application Specific Parameters._
    The byte, bOffset, shall contain an offset within the array pointing to the length of the instance AID.
    The byte, bLength, shall contain a length indicating the total length of the above-defined data in the array.
    The applet is required to utilize the instance AID as a parameter when invoking the register (byte []
    bArray, short bOffset, byte bLength) method of the Class Applet of the Java Card� 2.1.1
    Application Programming Interface specification.

  • Repost: Problem with byte array

    i wrote the following code:
    public class Test {
    byte [] ba = new byte[10];
    void print(String s) { System.out.println(s); }
    void printInitialValues() {
    for (int i=0; i<10; i++)
    ba = (byte)0;
    //System.arraycopy("asdf".getBytes(), 0, ba, 0, 4);*/
    print("byte array " + ba);
    public static void main(String[] args) {
    Test iv = new Test();
    iv.printInitialValues();
    }why the output isn't the string of the serial '0', instead, it seems the random output.
    when i put the line "System...." to the code, the result is the same.
    Can anybody tell me why?
    Regards,
    Jason

    Your byte[] is an object of the type Array. Array does
    not override toString(), and thus you get the default
    Object.toString() behavior. If you want to print out
    the array elements, you'll need to iterate through the
    array manually.And in 1.5 you can use this:
    Arrays.toString(byteArray);/Kaj

  • Problem with byte array

    i wrote the following code:
    public class Test {
    byte [] ba = new byte[10];
    void print(String s) { System.out.println(s); }
    void printInitialValues() {
    for (int i=0; i<10; i++)
    ba[i] = (byte)0;
    //System.arraycopy("asdf".getBytes(), 0, ba, 0, 4);*/
    print("byte array " + ba);
    public static void main(String[] args) {
    Test iv = new Test();
    iv.printInitialValues();
    why the output isn't the string of serial '0', instead, it seems the random output.
    when i put the line "System...." to the code, the result is the same.
    Anybody can tell me why?
    Regards,
    Jason

    Continued [url http://forum.java.sun.com/thread.jsp?forum=31&thread=551032&tstart=0&trange=15]here.

  • Encoding format of a byte array

    Hi,
    How can I get the UTF-encodingformat of a byte array?
    thanks
    Olek

    Hm then can you make a suggestion why this :
    java.io.EOFException
            at java.io.DataInputStream.readFully(DataInputStream.java:180)
            at java.io.DataInputStream.readUTF(DataInputStream.java:592)
            at java.io.DataInputStream.readUTF(DataInputStream.java:547)
            at org.bouncycastle.jce.provider.JDKKeyStore.loadStore(Unknown Source)can occur?
    I try to load a keystore from a ByteArrayInputStream ... the byte array is encrypted and later decrypted ...
    can it be, that the cipher change the format of the characters?
    this is equal to my posting here.
    Olek

  • Byte array size changes

    For some reason the size of my byte arrays change, and it is causing problems using an AES Cipher.
    The length of the byte array is 16 when I first encrypt text, but when I try and decrypt it, it tells me the length is 29. Then I have an IllegalBlockSizeException.
    Can someone explain how to overcome this problem?
    I used the UTF-8 encoding on Ubuntu 8.04

    TamalinJava wrote:
    For some reason the size of my byte arrays change, and it is causing problems using an AES Cipher.A byte[] has a fixed size, you cannot change it.
    The length of the byte array is 16 when I first encrypt text, but when I try and decrypt it, it tells me the length is 29. Then I have an IllegalBlockSizeException.
    I used the UTF-8 encoding on Ubuntu 8.04This is your problem. It translates values >= 128 to be two characters.
    Can someone explain how to overcome this problem?Don't try to write binary data as if it were text. (Write it as binary data)

  • 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 in JSON reply

    Hi guys,
    I'm exchanging some data between .net webservice and flex
    with JSON. This is a JSON reply:
    <string>
    {"uid":"23","photos":[[255,216,255,224,0,16,74,70,73,70,0,1,1,1,0,72,0,72,0,0,255,219,0,67 ,0,8,6,6,7,6,5,8,7,7,7,9,9,8,10,12,20
    </string>
    It is serialized this class:
    public class UserPhotoBytes
    public string uid;
    public ArrayList photos;
    public UserPhotoBytes()
    Where photos is THE ARRAY OF BYTE ARRAYS. Then in Flex I
    deserialize it with:
    public function
    onPhotoReceived(event:GetUserPhotoResultEvent):void
    var myImg:Image = new Image();
    var rawData:String = String(event.result);
    var userPhoto:Object = JSON.decode(rawData) as Object
    _user.photos = userPhoto.photos as Array;
    myImg.data = _user.photos[0] as ByteArray;
    But I think it cannot convert the string value of byte array
    of JSON object to real byte representation. Or am I missing
    something else ? Thank you very much for the response

    Hi,
    I am opening the file with wordpad.
    when opening the file the output i could see is:
    U
    wU
    w
    which is ASCII value I guess. Pls tell me if my guess is wrong & value is in binary format only.I am somewhat confused :O.
    As per the client requirement he should get the value in the file as binary format and not as ASCII.
    I hope i am not misleading you and hope that now you got what is my problem.
    Neha

Maybe you are looking for