Obtain byte array from StringBuffer

Hi!
I have a String Buffer containig the string of an xml file! Then I need to parse this file. How can I obtain an InputStream or ByteArrayInputStream from the StringBuffer?
Thanks!

Or instead of converting it to bytes (which runs the risk of damaging non-ASCII characters if your system's default charset is not UTF-8), just make it a StringReader and parse that:parse(new InputSource(new StringReader(sb.toString()));

Similar Messages

  • How do I get a byte array from an object passed into the JNI?

    This is what my java code looks like:
    public class streamedData
    protected byte[] m_value = null;
    public byte[] getByteArray ()
    return m_value;
    /* code not pertaining to this question snipped. */
    jclass streamedDataClass = env->GetObjectClass(jstreamedData);
    // Get methodIDs for the various NPKI_Extension methods
    value = env->GetMethodID(streamedDataClass, "getByteArray", "()[B");
    lstreamedData->value = (unsigned char *)malloc (lstreamedData->length);
    if (lstreamedData->value == NULL)
    return INSUFFICIENT_MEMORY;
    memset (lstreamedData->value, 0, lstreamedData->length);
    memcpy (lstreamedData->value, env->CallByteMethodA(streamedDataClass, value, NULL), lstreamedData->length);
    This is not working.
    My question is, how do I get a copy of or read m_value in the JNI layer? Do I have to make the byte array public and access it as a field ID?
    Any help would be appreciated. Why oh why can't there be a CallByteArrayMethod????

    My question is, how do I get a copy of or read m_value in the JNI layer? Do I have to make the byte array public and access it as a field ID?
    You can retrieve a handle to the byte array, through a method call, as you're doing now, or by directly accessing it through GetFieldID.
    In the case of the method call, you'll want to do:jmethodID getByteArrayMethod = env->GetMethodID(streamedDataClass, "getByteArray", "()[B");
    jbyteArray byteArray = static_cast<jbyteArray>( env->CallObjectMethod( jstreamedData, getByteArrayMethod ) );In the case of field access, you can do:jfieldID m_valueFieldID = env->GetFieldID( streamedDataClass, "m_value", "[B" );
    jbyteArray byteArray = static_cast<jbyteArray>( env->GetObjectField( jstreamedData, m_valueFieldID ) );Once you have byteArray, you need to access it using the array operations:lstreamedData->value = env->GetByteArrayElements( byteArray, 0 );
    // Do what you want to do, then release the array
    env->ReleaseByteArrayElements( byteArray, lstreamedData->value, 0 );As always, Jace, http://jace.reyelts.com/jace, makes this easier. For example,void printByteArray( jobject jstreamedData ) {
      streamedData data( jstreamedData );
      JArray<JByte> byteArray = streamedData.m_value();
      for ( int i = 0; i < byteArray.length(); ++i ) {
        cout << byteArray[ i ];
    }God bless,
    -Toby Reyelts

  • Byte Array from SQL Reporting Service

    I am calling the Render method of the Microsoft SQL Reporting
    Service's ReportExecution web service. It returns a Byte array in
    the lastResult object. I am having the hardest time figuring out a
    way to convert that byte array into something I can use in Flex.
    The byte array, once converted into a more user friendly format,
    will contain the rendered version of a SQL Report in whatever
    format I have specified...in this case it is XML. Any input or
    suggestions would be appreciated.

    This is a little late, I know. but I just spent the day
    struggling with this very issue. Hopefully this can help someone
    else in the future. Here's my solution...
    on MX:Operation -- result="fillXML()"
    then
    private function fillXML(): void {
    var x:XML = new
    XML(wsProps.GetDatasetData.lastResult.toString());
    ...do what you need with your xml...
    I use an XMLList node of the result as the source property
    for an XMLListCollection bound to a datagrid. Let me know if you
    need more help to get it working. It works like a charm now that I
    figured that out. I don't know if it's a slimy hack, or not, but it
    gets the job done.

  • How to get byte array from jpg in resource for Image XObject?

    Hi,
    Does anyone know how to get an array of bytes from a jpg from resource without an external library except MFC?
    The array of bytes is needed to create an Image XObject so it can be included in an appearance for an annotation.

    Sounds like a standard Windows programming question, not specific to the SDK.

  • How to get correct byte array from String

    I have a string which contains binary value from 0 to 255. Now, if I use String.getBytes(),all the chars in the string which range from 128 to 160 will be convert to 63.
    What's the problem?

    You're assuming that you're working with Ascii values.
    You're actually working with Unicode values.
    When you use getChar() on a String, you get back a 16bit integer, the unicode index. When you do a getBytes() the Unicode values get mapped back to the default codepage of your machine.
    Eg. on an english pc, the default locale is Windows latin, codepage 1252. On non-english pcs, it could be any encoding scheme.
    If you're on a machine set up for a chinese locale, then the Unicode
    values get mapped to your chinese codepage. The extended ascii values,
    above 127 may not be defined in your codepage.
    Try String.getBytes ( "Cp1252" );
    Although I suspect that, whatever you're trying to do, it's probably not the right approach....
    regards,
    Owen

  • Make sound file from byte array?

    Ok say I have a program that gets a byte array from a sound file and then randomly removes some of the samples from the array, so that instead of having a value the bytes are just zeroes. I then want to play my new byte array. Here is the code I try to use but when I use it nothing happens.
    AudioFormat = ((AudioInputStream) AudioSystem.getAudioInputStream(**The Original Sound File**)).getFormat();
    int numBytesRead = 0;
    DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat);
    SourceDataLine sourceDataLineTemp = (SourceDataLine)AudioSystem.getLine(dataLineInfo);
    sourceDataLineTemp.write(audioArray, 0, audioArray.length);(Try..catch removed for clarity.)
    Also, is it possible to convert a byte array to a .wav sound file?

    Im pretty sure if you just write that byte array to disk and open it as a wav file that will do the trick, because thats all a wav file is anyways, a stream of bytes representing audio

  • Sending publickey through the network as a byte array.

    I send client public key form server to client as a byte array through the network. I'm sruggling when I get that byte array from client side and again assign to the PublicKey variable. Anyone can give me any hints how can I extract the public key from the byte array.
    Thank you

    If your public key is from an X509 certificate, you can use the X509EncodedKeySpec class.

  • Sending a Byte array through a socket

    Can someone please tell me how i can send a Byte array from a client to a sever using sockets?
    Thanks
    Mark

    This tutorial should do the trick:
    http://java.sun.com/docs/books/tutorial/networking/sockets/index.html

  • 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

  • Retun of object or Array From webservice

    Thanks pekka,
    you are right...
    It is also possible to manage the ByteStream by returning the byte[] array from web services, but the issue is when the response reaches to the client... the invoke method returns object ...as
    byte[] ret = (byte[]) call.invoke( new Object[] { "Any String" } );
    At this point the axis server throws an error.... regarding the cast of Object type to byte array... (ClassCastException)... Due to this error i thought to return ByreArrayOutputStream object from webservice function......
    Although the return of byte[] will also work for me.... but the wholw issue struck at client at client side during typecasting of returned object from web services.....
    please suggest any solution.... for its casting...
    Thanks Very much...
    Gaurav

    Dear jpday,
    Have you seen this tutorial?
    Web Services in LabVIEW 
    http://zone.ni.com/devzone/cda/tut/p/id/7350
    attached to it you will find a zip file named webservicesdemo. This demo contains a VI called Function Generator Main, which shows how to convert an array to an XML string, which you can then output from the web service VI (Function Generator Main shows how to do this). 
    Hope this helps!
    ~Nate 

  • ImageIcon and byte array

    ImageIcon II = new ImageIcon( myUrl );
    Will give me an ImageIcon based upon the URL given.
    I know an alternate constructor ImageIcon II = new ImageIcon( myByteArray );
    Whereby one can get an ImageIcon based on a given ByteArray.
    Is there any way to go the other way?
    I'd like to get a byte array from a given ImageIcon.
    Any suggestions?

    The reason for the post is that I'd like to store a bunch of images (I don't know in advance how big this bunch is going to be so I'm putting the collection in an ArrayList) in one file. I can do this with a ArrayList of byte-arrays or with a Vector/ArrayList of ImageIcons.
    Will an ArrayList of byte arrays containing byte-arrays differ much in size with a ArrayList of ImageIcons? The Serilaized Form section of the API does not give me very useful information in this regard. I'm thinking putting byte arrays in the ArrayList will save me some space, but if this savings isn't very much I'm going to go ahaead and stroe a Vector/ArrayList of ImageIcons.

  • 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 Do I Load An Animated GIF Into PictureBox Control From Byte Array?

    I'm having a problem with loading an animated GIF int a picturebox control in a C# program after it has been converted to a base64 string, then converted to a byte array, then written to binary, then converted to a base64 string again, then converted to
    a byte array, then loaded into a memory stream and finally into a picturebox control.
    Here's the step-by-step code I've written:
    1. First I open an animated GIF from a file and load it directly into a picturebox control. It animates just fine.
    2. Next I convert the image in the picturebox control (pbTitlePageImage) to a base64 string as shown in the code below:
                    if (pbTitlePageImage.Image != null)
                        string Image2BConverted;
                        using (Bitmap bm = new Bitmap(pbTitlePageImage.Image))
                            using (MemoryStream ms = new MemoryStream())
                                bm.Save(ms, ImageFormat.Jpeg);
                                Image2BConverted = Convert.ToBase64String(ms.ToArray());
                                GameInfo.TitlePageImage = Image2BConverted;
                                ms.Close();
                                GameInfo.TitlePageImagePresent = true;
                                ProjectNeedsSaving = true;
    3. Then I write the base64 string to a binary file using FileStream and BinaryWriter.
    4. Next I get the image from the binary file using FileStream and BinaryReader and assign it to a string variable. It is now a base64 string again.
    5. Next I load the base64 string into a byte array, then I load it into StreamReader and finally into the picturebox control (pbGameImages) as shown in the code below:
    byte[] TitlePageImageBuffer = Convert.FromBase64String(GameInfo.TitlePageImage);
                            MemoryStream memTitlePageImageStream = new MemoryStream(TitlePageImageBuffer, 0, TitlePageImageBuffer.Length);
                            memTitlePageImageStream.Write(TitlePageImageBuffer, 0, TitlePageImageBuffer.Length);
                            memTitlePageImageStream.Position = 0;
                            pbGameImages.Image = Image.FromStream(memTitlePageImageStream, true);
                            memTitlePageImageStream.Close();
                            memTitlePageImageStream = null;
                            TitlePageImageBuffer = null;
    This step-by-step will work with all image file types except animated GIFs (standard GIFs work fine). It looks like it's just taking one frame from the animation and loading it into the picturebox. I need to be able to load the entire animation. Does any of
    the code above cause the animation to be lost? Any ideas?

    There is an ImageAnimator so you may not need to use byte array instead.
    ImageAnimator.Animate Method
    http://msdn.microsoft.com/en-us/library/system.drawing.imageanimator.animate(v=vs.110).aspx
    chanmm
    chanmm

  • 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 do I store an Int, a short, and multiple bytes from file in byte array

    I'm attempting to do this for a project but can't figure out how to store the three values in one byte array. This is what i've tried
    public void send(byte[] input)
              // TODO
              ByteArrayInputStream bais = new ByteArrayInputStream(input);
              ByteArrayOutputStream baos = new ByteArrayOutputStream();
              DataOutputStream dos = new DataOutputStream(baos);
              byte[] pData = new byte[100];
              try {
                   dos.writeShort(checkSum);
                   dos.writeInt(nextSeqNum);
                   pData=baos.toByteArray();
                   bais.read(pData);
              } catch (IOException e) {
              DatagramPacket dgp = new DatagramPacket(pData, pData.length);When i set pData=baos.toByteArray() it changes the size and then stops me from being able to read the other 94 bytes into the array to send. Any ideas?

    You don't need the ByteArrayInputStream at all.
    dos.writeShort(checkSum);
    dos.writeInt(nextSeqNum);
    dos.write(input);
    pData = baos.toByteArray();
    When i set pData=baos.toByteArray() it changes the sizeNo, it makes it refer to a new byte[] array containing what you've written to the BAOS. That's what it's supposed to do.

Maybe you are looking for