How to redirect output to a byte array?

I've Googled this, and looked around in the tutorials, but I haven't found a simple example of how to assign an output to a byte array. Maybe I'm just too much of a newbie to know how to navigate the documentation, but...
What I need is for this code (which does exactly what I want) to put the output in a byte array instead of in the file "test.txt". How do I accomplish that?
Thanks,
--gary
FileWriter writer = null;
        try {
          writer = new FileWriter("test.txt");
            MinimalHTMLWriter htmlWriter = new MinimalHTMLWriter(writer,
              (StyledDocument)textRegion.getDocument());
          htmlWriter.write();
        catch (IOException ex) {
            ... etc...

Thanks, That works fine!
--gary                                                                                                                                                                                                                               

Similar Messages

  • How to redirect output of an OS command to a stream???

    how can i redirect the output of an OS command (such as 'ls' in linux or 'dir' in windows) to a io stream???
    ....for example, assume i'm having a textbox and a button...when i click the button , i need the output of 'ls' to be in the textbox....i think execution of the command could be accomplished by Runtime's exec() ...but how to redirect outputs???

    You should find what you are looking for here:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • How to get a string or byte array representation of an Image/BufferedImage?

    I have a java.awt.Image object that I want to transfer to a server application (.NET) through a http post request.
    To do that I would like to encode the Image to jpeg format and convert it to a string or byte array to be able to send it in a way that the receiver application (.NET) could handle. So, I've tried to do like this.
    private void send(Image image) {
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        try {
            BufferedImage buffImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            ImageIcon imageIcon = new ImageIcon(image);
            ImageObserver observer = imageIcon.getImageObserver();
            buffImage.getGraphics().setColor(new Color(255, 255, 255));
            buffImage.getGraphics().fillRect(0, 0, width, height);
            buffImage.getGraphics().drawImage(imageIcon.getImage(), 0, 0, observer);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(stream);
            jpeg.encode(buffImage);
            URL url = new URL(/* my url... */);
            URLConnection connection = url.openConnection();
            String boundary = "--------" + Long.toHexString(System.currentTimeMillis());
            connection.setRequestProperty("method", "POST");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            String output = "--" + boundary + "\r\n"
                          + "Content-Disposition: form-data; name=\"myImage\"; filename=\"myFilename.jpg\"\r\n"
                          + "Content-Type: image/jpeg\r\n"
                          + "Content-Transfer-Encoding: base64\r\n\r\n"
                          + new String(stream.toByteArray())
                          + "\r\n--" + boundary + "--\r\n";
            connection.setDoOutput(true);
            connection.getOutputStream().write(output.getBytes());
            connection.connect();
        } catch {
    }This code works, but the image I get when I save it from the receiver application is distorted. The width and height is correct, but the content and colors are really weird. I tried to set different image types (first line inside the try-block), and this gave me different distorsions, but no image type gave me the correct image.
    Maybe I should say that I can display the original Image object on screen correctly.
    I also realized that the Image object is an instance of BufferedImage, so I thought I could skip the first six lines inside the try-block, but that doesn't help. This way I don't have to set the image type in the constructor, but the result still is color distorted.
    Any ideas on how to get from an Image/BufferedImage to a string or byte array representation of the image in jpeg format?

    Here you go:
      private static void send(BufferedImage image) throws Exception
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpeg", byteArrayOutputStream);
        byte[] imageByteArray = byteArrayOutputStream.toByteArray();
        URL url = new URL("http://<host>:<port>");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(imageByteArray, 0, imageByteArray.length);
        outputStream.close();
        connection.connect();
        // alternative to connect is to get & close the input stream
        // connection.getInputStream().close();
      }

  • How can i convert object to byte array very*100 fast?

    i need to transfer a object by datagram packet in embeded system.
    i make a code fallowing sequence.
    1) convert object to byte array ( i append object attribute to byte[] sequencailly )
    2) send the byte array by datagram packet ( by JNI )
    but, it's not satisfied my requirement.
    it must be finished in 1ms.
    but, converting is spending 2ms.
    network speed is not bottleneck. ( transfer time is 0.3ms and packet size is 4096 bytes )
    Using ObjectOutputStream is very slow, so i'm using this way.
    is there antoher way? or how can i improve?
    Edited by: JongpilKim on May 17, 2009 10:48 PM
    Edited by: JongpilKim on May 17, 2009 10:51 PM
    Edited by: JongpilKim on May 17, 2009 10:53 PM

    thanks a lot for your reply.
    now, i use udp socket for communication, but, i must use hardware pci communication later.
    so, i wrap the communication logic to use jni.
    for convert a object to byte array,
    i used ObjectInputStream before, but it was so slow.
    so, i change the implementation to use byte array directly, like ByteBuffer.
    ex)
    public class ByteArrayHelper {
    private byte[] buf = new byte[1024];
    int idx = 0;
    public void putInt(int val){
    buf[idx++] = (byte)(val & 0xff);
    buf[idx++] = (byte)((val>>8) & 0xff);
    buf[idx++] = (byte)((val>>16) & 0xff);
    buf[idx++] = (byte)((val>>24) & 0xff);
    public void putDouble(double val){ .... }
    public void putFloat(float val){ ... }
    public byte[] toByteArray(){ return this.buf; }
    public class PacketData {
    priavte int a;
    private int b;
    public byte[] getByteArray(){
    ByteArrayHelper helper = new ByteArrayHelper();
    helper.putInt(a);
    helper.putInt(b);
    return helper.toByteArray();
    but, it's not enough.
    is there another way to send a object data?
    in java language, i can't access memory directly.
    in c language, if i use struct, i can send struct data to copy memory by socket and it's very fast.
    Edited by: JongpilKim on May 18, 2009 5:26 PM

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

  • How can I convert  AudioInputStream to  byte array ?

    Hi
    I want to convert audioinputStream to bytearry?
    i try like this
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
         int c = 0;
         while (true) {
         try {
                        c = audioInputStream.read();
                   } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
         if (c == -1)
         break;
         baos.write(c);
    but...
    java.io.IOException: cannot read a single byte if frame size != 1
    occur...
    plz help me..

    Hi,
    I haven't tried, but from the API doc I would suggest:
    Retrieve the frame size by
    int fs = audioInputStream.getFormat().getFrameSize();Allocate a byte array with at least this size and read full frames:
    byte[] buf = new byte[fs];
    int sz = audioInputStream.read(buf);Write also to your baos a full frame:
    baos.write(buf, 0, sz);

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

  • How to make use of byte array to perform credit and debit in Wallet Applet

    Hi,
    Can anyone please explain me how to use the concept of byte arrays.. to perform credit and debit operations of a 6byte amount. Say for example.. the amount contains 3 bytes whole number, 1 byte decimal dot and 2 bytes fractional part.
    It would be helpful if anyone could post a code snippet.. that way i can undersatnd easily.
    Thanks in Advance
    Nara

    Hello
    as explained in the other topic, remember your high school years and how you leart to add numbers.
    then, reproduce these algorithms for base-256 numbers.
    fractional? just google about fixed point math and floating point math. The first one is easier, as they are managed as integers.
    example, you want to store 1,42€. Then you decide the real number to deal with is N*100, and you store 142. You get 2 decimal places of precision.
    in the computer world it's easier to store n*256 as it's just a byte shift.
    then the addition operations are the same, and you just interpret the values as fractional numbers.
    regards
    sebastien

  • How to know the length of a Byte array?

    how to know the length a byte array if it is an argument of the method, e.g.
    public byte[] hash(byte[] data) throws Exception
    I wanna store the length of data into a integer in the method of hash, but no idea how to get it
    THanks!

    to conclude:
    I am a newbie, I wanna know , those "System"
    methods as well.What exactly does that have to do with your original question?
    or instance:
    System.arrowcopy() , where can I find the
    definition also?You probably meant System.arraycopy. The documentation is called JavaDoc and for Java 1.5 (a.k.a. 5.0) it can be found here: http://java.sun.com/j2se/1.5.0/docs/api/index.html
    If you've not yet found the API documentation, then I'm pretty sure you should start with some tutorials, they probably point to all the interesting documentation as well.

  • How to convert a Image object to byte Array?

    Who can tell me, how to convert Image object to byte Array?
    Example:
    public byte[] convertImage(Image img) {
    byte[] b = new byte...........
    return b;

    Hello,
    any way would suit me, I just need a way to convert Image or BufferedImage to a byte[], so that I can save them. Actually I need to save both jpg and gif files without using any 3rd party classes. Please help me out.
    thanx and best wishes

  • How can I convert stream to byte and byte to stream

    I got a IInputStream from BackgroundDownloader operation, how can I convert it to byte array? I try to convert it to buffer and after that to bytes, but it's always throw exception.
    function decryptStream(inputStream, totalBytes) {
    var reader = new Windows.Storage.Streams.DataReader(inputStream);
    var iBuffer = reader.readBuffer(totalBytes);
    var bytes = Windows.Security.Cryptography.CryptographicBuffer.copyToByteArray(iBuffer);
    Could I have examples about that?

    Hi Jeft,
    In my program, I have a BackgroundDownloader to download an image. When we have result, I will convert it to bytes array.
    if (p.hasResponseChanged && imageStream == null) {
    imageStream = operation.getResultStreamAt(0);
    if (!p.hasResponseChanged && imageStream != null) {
    decryptStream(imageStream, p['bytesReceived']);

  • Java.sql.SQLException: Byte array not long enough

    using thin jdbc returned this exception seems to be connected to the length of the statment:
    ////////create a prepared statement////////
    preUpdateStatement = dbConnection.prepareStatement(updateStatement.toString());
    // build data output stream on byte array output stream
    ByteArrayOutputStream byte_os = new ByteArrayOutputStream();
    DataOutputStream data_os = new DataOutputStream(byte_os);
    // write chars to data output stream
    data_os.writeChars(((Element)m_values_vector.elementAt(i)).m_value);
    // create input stream and pass it to prepared statement
    ByteArrayInputStream byte_is = new ByteArrayInputStream(byte_os.toByteArray());
    preStatement.setUnicodeStream(i+1, byte_is, byte_os.toByteArray().length);
    // execute
    preUpdateStatement.executeUpdate();
    preUpdateStatement.close();
    null

    stack is:
    java.sql.SQLException: Io exception: Char array not long enough: javaCharsToUtf8Bytes
    at java.lang.Throwable.<init>(Compiled Code)
    at java.lang.Exception.<init>(Compiled Code)
    at java.sql.SQLException.<init>(Compiled Code)
    at oracle.jdbc.dbaccess.DBError.throwSqlException(Compiled Code)
    at oracle.jdbc.dbaccess.DBError.throwSqlException(Compiled Code)
    at oracle.jdbc.dbaccess.DBError.throwSqlException(Compiled Code)
    at oracle.jdbc.driver.OracleStatement.executeNonQuery(Compiled Code)
    at oracle.jdbc.driver.OracleStatement.doExecuteOther(Compiled Code)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithBatch(Compiled Code)
    at oracle.jdbc.driver.OracleStatement.doExecute(Compiled Code)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(Compiled Code)
    at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(Compiled Code)

  • Play flv byte array in Air Application

    I'm trying to load and play an FLV from a ByteArray in Air application . I have created small dummy application in  which l am readiong flv from file system .After reading flv file i have byte array so can you please help me out in thi how to p-lay flv from byte array.
    I have searched the web for awnsers and didn't find anything .
    Any help, ideas or something?

    Hi Giuseppe,
    what I do is:
    1. create a file using Captivate
    2. i place a .flv video in this file
    3. save the file as .swf
    4. then i go to dreamweaver and put the swf on a html page.
    Now:
    when viewed in a browser, everything runs fine.
    when i pack this page into an air application (in dreamweaver) the video does not appear,
    instead I get this "Connection Error"
    I do not know a console or log file.
    However, I learned that there is a .xml file located in the same AIR folder that you publish in.
    In this .xml file there is a setting :transparency. in order to playt a .flv file this must not be be "transparent"!
    (i read this somewhere in the net)
    hope that helps
    I will talk to a professional programmer, if I have any news, i will let you know
    Claus

  • How to put a String into a byte array

    How can i put a String into a byte array byte[]. So that i can send it to the serial port for output to an LCD display. Cheers David

    javadocs for String
    getBytes
    public byte[] getBytes()
    Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
    Returns:
    The resultant byte arraySince:
    JDK1.1

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

Maybe you are looking for

  • How to change "_review" at the end of the file name in Acrobat XI Pro

    For our business workflow, we need to be able to change the "_review" at the end of the file name when creating shared-review PDFs. Older versions of Acrobat Pro allowed me to customize the ending of the file name before it was saved as a shared revi

  • CS4 will not create a movie file, it just stops!

    Can anyone help, I am at my wits end trying to create a movie file and have tried over half a dozen formats without success. Everything appears to be going well then it just stops! It was fine the last time I tried it 3 months ago. Waiting in anticip

  • Blank Pop up Windows

    I have been having a problem with an installation of Reader. The pop up window for printing options is showing up with no text on the buttons. Someone advised me to check 'preferences' but that window is also blank [no text] so I cannot adjust anythi

  • My friends aren't getting my "delivered" iMessages

    The title pretty much says it all. My friends have their read reciepts on too and none of them have seen them. What do I do to fix this problem?

  • Nokia 2730classic java applications cannot access ...

    I have nokia2730classic and when i access java applications through internet it doesnot work.but it works with default opera browser.moreover, i am not able to upgrade my browser. Please help