Example usage for java.io ByteArrayOutputStream flush

List of usage examples for java.io ByteArrayOutputStream flush

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:com.oculusinfo.tile.util.AvroJSONConverter.java

/**
 * Convert an Avro input stream into a JSON object
 * //ww w .j a v  a2  s.c o  m
 * @param stream The input data
 * @return A JSON representation of the input data
 * @throws IOException
 * @throws JSONException
 */
public static JSONObject convert(InputStream stream) throws IOException, JSONException {
    SeekableInput input = new SeekableByteArrayInput(IOUtils.toByteArray(stream));
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    // Conversion code taken from org.apache.avro.tool.DataFileReadTool
    GenericDatumReader<Object> reader = new GenericDatumReader<Object>();
    FileReader<Object> fileReader = DataFileReader.openReader(input, reader);
    try {
        Schema schema = fileReader.getSchema();
        DatumWriter<Object> writer = new GenericDatumWriter<Object>(schema);
        JsonEncoder encoder = EncoderFactory.get().jsonEncoder(schema, output);
        for (Object datum : fileReader) {
            encoder.configure(output);
            writer.write(datum, encoder);
            encoder.flush();
            // For some reason, we only contain one record, but the 
            // decoding thinks we contain more and fails; so just break 
            // after our first one.
            break;
        }
        output.flush();
    } finally {
        fileReader.close();
    }
    String jsonString = output.toString("UTF-8");
    return new JSONObject(jsonString);
}

From source file:net.sf.jasperreports.engine.util.JRLoader.java

/**
 *
 *///from   w w w .  j a  v  a 2 s . c  o m
public static byte[] loadBytes(InputStream is) throws JRException {
    ByteArrayOutputStream baos = null;

    try {
        baos = new ByteArrayOutputStream();

        byte[] bytes = new byte[10000];
        int ln = 0;
        while ((ln = is.read(bytes)) > 0) {
            baos.write(bytes, 0, ln);
        }

        baos.flush();
    } catch (IOException e) {
        throw new JRException(EXCEPTION_MESSAGE_KEY_BYTE_DATA_FROM_INPUT_STREAM_ERROR, null, e);
    } finally {
        if (baos != null) {
            try {
                baos.close();
            } catch (IOException e) {
            }
        }
    }

    return baos.toByteArray();
}

From source file:net.pms.util.UMSUtils.java

@SuppressWarnings("deprecation")
public static InputStream scaleThumb(InputStream in, RendererConfiguration r) throws IOException {
    if (in == null) {
        return in;
    }/* w  w  w  .j  a v a 2 s . c om*/
    String ts = r.getThumbSize();
    if (StringUtils.isEmpty(ts) && StringUtils.isEmpty(r.getThumbBG())) {
        // no need to convert here
        return in;
    }
    int w;
    int h;
    Color col = null;
    BufferedImage img;
    try {
        img = ImageIO.read(in);
    } catch (Exception e) {
        // catch whatever is thrown at us
        // we can at least log it
        LOGGER.debug("couldn't read thumb to manipulate it " + e);
        img = null; // to make sure
    }
    if (img == null) {
        return in;
    }
    w = img.getWidth();
    h = img.getHeight();
    if (StringUtils.isNotEmpty(ts)) {
        // size limit thumbnail
        w = getHW(ts.split("x"), 0);
        h = getHW(ts.split("x"), 1);
        if (w == 0 || h == 0) {
            LOGGER.debug("bad thumb size {} skip scaling", ts);
            w = h = 0; // just to make sure
        }
    }
    if (StringUtils.isNotEmpty(r.getThumbBG())) {
        try {
            Field field = Color.class.getField(r.getThumbBG());
            col = (Color) field.get(null);
        } catch (Exception e) {
            LOGGER.debug("bad color name " + r.getThumbBG());
        }
    }
    if (w == 0 && h == 0 && col == null) {
        return in;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    BufferedImage img1 = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = img1.createGraphics();
    if (col != null) {
        g.setColor(col);
    }
    g.fillRect(0, 0, w, h);
    g.drawImage(img, 0, 0, w, h, null);
    ImageIO.write(img1, "jpeg", out);
    out.flush();
    return new ByteArrayInputStream(out.toByteArray());
}

From source file:main.java.vasolsim.common.file.ExamBuilder.java

/**
 * Writes an exam to an XML file//from  w w w  .  j  a v a 2s.  c om
 *
 * @param exam      the exam to be written
 * @param examFile  the target file
 * @param password  the passphrase locking the restricted content
 * @param overwrite if an existing file can be overwritten
 *
 * @return if the write was successful
 *
 * @throws VaSolSimException
 */
public static boolean writeExam(@Nonnull Exam exam, @Nonnull File examFile, @Nonnull String password,
        boolean overwrite) throws VaSolSimException {
    logger.info("beginning exam export -> " + exam.getTestName());

    logger.debug("checking export destination...");

    /*
     * check the file creation status and handle it
     */
    //if it exists
    if (examFile.isFile()) {
        logger.trace("exam file exists, checking overwrite...");

        //can't overwrite
        if (!overwrite) {
            logger.error("file already present and cannot overwrite");
            throw new VaSolSimException(ERROR_MESSAGE_FILE_ALREADY_EXISTS);
        }
        //can overwrite, clear the existing file
        else {
            logger.trace("overwriting...");
            PrintWriter printWriter;
            try {
                printWriter = new PrintWriter(examFile);
            } catch (FileNotFoundException e) {
                logger.error("internal file presence check failed", e);
                throw new VaSolSimException(ERROR_MESSAGE_FILE_NOT_FOUND_AFTER_INTERNAL_CHECK);
            }

            printWriter.print("");
            printWriter.close();
        }
    }
    //no file, create one
    else {
        logger.trace("exam file does not exist, creating...");

        if (!examFile.getParentFile().isDirectory() && !examFile.getParentFile().mkdirs()) {
            logger.error("could not create empty directories for export");
            throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_DIRS);
        }

        try {
            logger.trace("creating files...");
            if (!examFile.createNewFile()) {
                logger.error("could not create empty file for export");
                throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_FILE);
            }
        } catch (IOException e) {
            logger.error("io error on empty file creation", e);
            throw new VaSolSimException(ERROR_MESSAGE_CREATE_FILE_EXCEPTION);
        }
    }

    logger.debug("initializing weak cryptography scheme...");

    /*
     * initialize the cryptography system
     */
    String encryptedHash;
    Cipher encryptionCipher;
    try {
        logger.trace("hashing password into key...");
        //hash the password
        byte[] hash;
        MessageDigest msgDigest = MessageDigest.getInstance("SHA-512");
        msgDigest.update(password.getBytes());
        hash = GenericUtils.validate512HashTo128Hash(msgDigest.digest());

        logger.trace("initializing cipher");
        encryptionCipher = GenericUtils.initCrypto(hash, Cipher.ENCRYPT_MODE);

        encryptedHash = GenericUtils
                .convertBytesToHexString(GenericUtils.applyCryptographicCipher(hash, encryptionCipher));
    } catch (NoSuchAlgorithmException e) {
        logger.error("FAILED. could not initialize crypto", e);
        throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD ALGORITHM\n" + e.toString() + "\n"
                + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e);
    }

    logger.debug("initializing the document builder...");

    /*
     * initialize the document
     */
    Document examDoc;
    Transformer examTransformer;
    try {
        logger.trace("create document builder factory instance -> create new doc");
        examDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

        logger.trace("set document properties");
        examTransformer = TransformerFactory.newInstance().newTransformer();
        examTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
        examTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
        examTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        examTransformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd");
        examTransformer.setOutputProperty(INDENTATION_KEY, "4");
    } catch (ParserConfigurationException e) {
        logger.error("parser was not configured correctly", e);
        throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_XML_PARSER_INITIALIZATION_EXCEPTION, e);
    } catch (TransformerConfigurationException e) {
        logger.error("transformer was not configured properly");
        throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_TRANSFORMER_CONFIGURATION, e);
    }

    logger.debug("building document...");

    /*
     * build exam info
     */
    logger.trace("attaching root...");
    Element root = examDoc.createElement(XML_ROOT_ELEMENT_NAME);
    examDoc.appendChild(root);

    logger.trace("attaching info...");
    Element info = examDoc.createElement(XML_INFO_ELEMENT_NAME);
    root.appendChild(info);

    //exam info
    logger.trace("attaching exam info...");
    GenericUtils.appendSubNode(XML_TEST_NAME_ELEMENT_NAME, exam.getTestName(), info, examDoc);
    GenericUtils.appendSubNode(XML_AUTHOR_NAME_ELEMENT_NAME, exam.getAuthorName(), info, examDoc);
    GenericUtils.appendSubNode(XML_SCHOOL_NAME_ELEMENT_NAME, exam.getSchoolName(), info, examDoc);
    GenericUtils.appendSubNode(XML_PERIOD_NAME_ELEMENT_NAME, exam.getPeriodName(), info, examDoc);
    GenericUtils.appendSubNode(XML_DATE_ELEMENT_NAME, exam.getDate(), info, examDoc);

    //start security xml section
    logger.trace("attaching security...");
    Element security = examDoc.createElement(XML_SECURITY_ELEMENT_NAME);
    root.appendChild(security);

    GenericUtils.appendSubNode(XML_ENCRYPTED_VALIDATION_HASH_ELEMENT_NAME, encryptedHash, security, examDoc);
    GenericUtils.appendSubNode(XML_PARAMETRIC_INITIALIZATION_VECTOR_ELEMENT_NAME,
            GenericUtils.convertBytesToHexString(encryptionCipher.getIV()), security, examDoc);
    GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_ELEMENT_NAME,
            Boolean.toString(exam.isReportingStats()), security, examDoc);
    GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_STANDALONE_ELEMENT_NAME,
            Boolean.toString(exam.isReportingStatsStandalone()), security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_DESTINATION_EMAIL_ADDRESS_ELEMENT_NAME,
            GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher(
                    exam.getStatsDestinationEmail() == null ? GenericUtils.NO_EMAIL.getBytes()
                            : exam.getStatsDestinationEmail().getBytes(),
                    encryptionCipher)),
            security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_EMAIL_ADDRESS_ELEMENT_NAME,
            GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher(
                    exam.getStatsSenderEmail() == null ? GenericUtils.NO_EMAIL.getBytes()
                            : exam.getStatsSenderEmail().getBytes(),
                    encryptionCipher)),
            security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_EMAIL_PASSWORD_ELEMENT_NAME,
            GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher(
                    exam.getStatsSenderPassword() == null ? GenericUtils.NO_DATA.getBytes()
                            : exam.getStatsSenderPassword().getBytes(),
                    encryptionCipher)),
            security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_ADDRESS_ELEMENT_NAME,
            GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher(
                    exam.getStatsSenderSMTPAddress() == null ? GenericUtils.NO_SMTP.getBytes()
                            : exam.getStatsSenderSMTPAddress().getBytes(),
                    encryptionCipher)),
            security, examDoc);
    GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_PORT_ELEMENT_NAME,
            GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher(
                    Integer.toString(exam.getStatsSenderSMTPPort()).getBytes(), encryptionCipher)),
            security, examDoc);

    logger.debug("checking exam content integrity...");
    ArrayList<QuestionSet> questionSets = exam.getQuestionSets();
    if (GenericUtils.checkExamIntegrity(exam).size() == 0) {
        logger.debug("exporting exam content...");
        for (int setsIndex = 0; setsIndex < questionSets.size(); setsIndex++) {
            QuestionSet qSet = questionSets.get(setsIndex);
            logger.trace("exporting question set -> " + qSet.getName());

            Element qSetElement = examDoc.createElement(XML_QUESTION_SET_ELEMENT_NAME);
            root.appendChild(qSetElement);

            GenericUtils.appendSubNode(XML_QUESTION_SET_ID_ELEMENT_NAME, Integer.toString(setsIndex + 1),
                    qSetElement, examDoc);
            GenericUtils.appendSubNode(XML_QUESTION_SET_NAME_ELEMENT_NAME,
                    (qSet.getName().equals("")) ? "Question Set " + (setsIndex + 1) : qSet.getName(),
                    qSetElement, examDoc);
            GenericUtils.appendSubNode(XML_QUESTION_SET_RESOURCE_TYPE_ELEMENT_NAME,
                    qSet.getResourceType().toString(), qSetElement, examDoc);

            if (qSet.getResourceType() != GenericUtils.ResourceType.NONE && qSet.getResources() != null) {
                logger.debug("exporting question set resources...");
                for (BufferedImage img : qSet.getResources()) {
                    if (img != null) {
                        try {
                            logger.trace("writing image...");
                            ByteArrayOutputStream out = new ByteArrayOutputStream();
                            ImageIO.write(img, "png", out);
                            out.flush();
                            GenericUtils.appendCDATASubNode(XML_QUESTION_SET_RESOURCE_DATA_ELEMENT_NAME,
                                    new String(Base64.encodeBase64(out.toByteArray())), qSetElement, examDoc);
                        } catch (IOException e) {
                            throw new VaSolSimException(
                                    "Error: cannot write images to byte array for transport");
                        }
                    }
                }
            }

            //TODO export problem in this subroutine
            for (int setIndex = 0; setIndex < qSet.getQuestions().size(); setIndex++) {
                Question question = qSet.getQuestions().get(setIndex);
                logger.trace("exporting question -> " + question.getName());

                Element qElement = examDoc.createElement(XML_QUESTION_ELEMENT_NAME);
                qSetElement.appendChild(qElement);

                logger.trace("question id -> " + setIndex);
                GenericUtils.appendSubNode(XML_QUESTION_ID_ELEMENT_NAME, Integer.toString(setIndex + 1),
                        qElement, examDoc);
                logger.trace("question name -> " + question.getName());
                GenericUtils.appendSubNode(XML_QUESTION_NAME_ELEMENT_NAME,
                        (question.getName().equals("")) ? "Question " + (setIndex + 1) : question.getName(),
                        qElement, examDoc);
                logger.trace("question test -> " + question.getQuestion());
                GenericUtils.appendSubNode(XML_QUESTION_TEXT_ELEMENT_NAME, question.getQuestion(), qElement,
                        examDoc);
                logger.trace("question answer scramble -> " + Boolean.toString(question.getScrambleAnswers()));
                GenericUtils.appendSubNode(XML_QUESTION_SCRAMBLE_ANSWERS_ELEMENT_NAME,
                        Boolean.toString(question.getScrambleAnswers()), qElement, examDoc);
                logger.trace("question answer order matters -> "
                        + Boolean.toString(question.getAnswerOrderMatters()));
                GenericUtils.appendSubNode(XML_QUESTION_REATIAN_ANSWER_ORDER_ELEMENT_NAME,
                        Boolean.toString(question.getAnswerOrderMatters()), qElement, examDoc);

                logger.debug("exporting correct answer choices...");
                for (AnswerChoice answer : question.getCorrectAnswerChoices()) {
                    logger.trace("exporting correct answer choice(s) -> " + answer.getAnswerText());
                    GenericUtils
                            .appendSubNode(XML_QUESTION_ENCRYPTED_ANSWER_HASH,
                                    GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher(
                                            answer.getAnswerText().getBytes(), encryptionCipher)),
                                    qElement, examDoc);
                }

                logger.debug("exporting answer choices...");
                for (int questionIndex = 0; questionIndex < question.getAnswerChoices()
                        .size(); questionIndex++) {
                    if (question.getAnswerChoices().get(questionIndex).isActive()) {
                        AnswerChoice ac = question.getAnswerChoices().get(questionIndex);
                        logger.trace("exporting answer choice -> " + ac.getAnswerText());

                        Element acElement = examDoc.createElement(XML_ANSWER_CHOICE_ELEMENT_NAME);
                        qElement.appendChild(acElement);

                        logger.trace("answer choice id -> " + questionIndex);
                        GenericUtils.appendSubNode(XML_ANSWER_CHOICE_ID_ELEMENT_NAME,
                                Integer.toString(questionIndex + 1), acElement, examDoc);
                        logger.trace("answer choice visible id -> " + ac.getVisibleChoiceID());
                        GenericUtils.appendSubNode(XML_ANSWER_CHOICE_VISIBLE_ID_ELEMENT_NAME,
                                ac.getVisibleChoiceID(), acElement, examDoc);
                        logger.trace("answer text -> " + ac.getAnswerText());
                        GenericUtils.appendSubNode(XML_ANSWER_TEXT_ELEMENT_NAME, ac.getAnswerText(), acElement,
                                examDoc);
                    }
                }
            }
        }
    } else {
        logger.error("integrity check failed");
        PopupManager.showMessage(errorsToOutput(GenericUtils.checkExamIntegrity(exam)));
        return false;
    }

    logger.debug("transforming exam...");
    try {
        examTransformer.transform(new DOMSource(examDoc), new StreamResult(examFile));
    } catch (TransformerException e) {
        logger.error("exam export failed (transformer error)", e);
        return false;
    }
    logger.debug("transformation done");

    logger.info("exam export successful");
    return true;
}

From source file:com.applozic.mobicommons.file.FileUtils.java

/**
 * This method will compressed Image to a pre-configured files.
 *
 * @param filePath/*from w w  w  .  j  a  va  2  s  .  c o  m*/
 * @param newFileName
 * @param maxFileSize
 * @return
 */
public static File compressImageFiles(String filePath, String newFileName, int maxFileSize) {

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);

    int actualHeight = options.outHeight;
    int actualWidth = options.outWidth;
    float imgRatio = actualWidth / actualHeight;
    int maxHeight = (2 * actualHeight) / 3;
    int maxWidth = (2 * actualWidth) / 3;

    float maxRatio = maxWidth / maxHeight;
    if (actualHeight > maxHeight || actualWidth > maxWidth) {
        if (imgRatio < maxRatio) {
            imgRatio = maxHeight / actualHeight;
            actualWidth = (int) (imgRatio * actualWidth);
            actualHeight = (int) maxHeight;
        } else if (imgRatio > maxRatio) {
            imgRatio = maxHeight / actualWidth;
            actualHeight = (int) (imgRatio * actualHeight);
            actualWidth = (int) maxWidth;
        } else {
            actualHeight = (int) maxHeight;
            actualWidth = (int) maxWidth;
        }
    }
    options.inSampleSize = ImageUtils.calculateInSampleSize(options, actualWidth, actualHeight);
    options.inJustDecodeBounds = false;

    options.inTempStorage = new byte[16 * 1024];

    try {
        bitmap = BitmapFactory.decodeFile(filePath, options);
    } catch (OutOfMemoryError exception) {
        exception.printStackTrace();

    }

    int streamLength = maxFileSize;
    int compressQuality = 100;// Maximum 20 loops to retry to maintain quality.
    ByteArrayOutputStream bmpStream = new ByteArrayOutputStream();
    while (streamLength >= maxFileSize && compressQuality > 50) {

        try {
            bmpStream.flush();
            bmpStream.reset();
        } catch (IOException e) {
            e.printStackTrace();
        }
        bitmap.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpStream);
        byte[] bmpPicByteArray = bmpStream.toByteArray();
        streamLength = bmpPicByteArray.length;
        if (BuildConfig.DEBUG) {
            Log.i("test upload", "Quality: " + compressQuality);
            Log.i("test upload", "Size: " + streamLength);
        }
        compressQuality -= 3;

    }

    FileOutputStream fo;
    try {
        fo = new FileOutputStream(newFileName);
        fo.write(bmpStream.toByteArray());
        fo.flush();
        fo.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return new File(newFileName);
}

From source file:com.feilong.commons.core.io.FileUtil.java

/**
 * ?ByteArray.//from  w ww  .j av  a2  s  .c om
 *
 * @param file
 *            file
 * @return byteArrayOutputStream.toByteArray();
 * @throws UncheckedIOException
 *             the unchecked io exception
 */
public static final byte[] convertFileToByteArray(File file) throws UncheckedIOException {
    InputStream inputStream = FileUtil.getFileInputStream(file);

    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    byte[] bytes = new byte[IOConstants.DEFAULT_BUFFER_LENGTH];
    int j;

    try {
        while ((j = bufferedInputStream.read(bytes)) != -1) {
            byteArrayOutputStream.write(bytes, 0, j);
        }
        byteArrayOutputStream.flush();

        return byteArrayOutputStream.toByteArray();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        try {
            // ???StreamClose.??Close
            // finally Block??close()
            byteArrayOutputStream.close();
            bufferedInputStream.close();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}

From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java

private static byte[] streamToByteArray(InputStream stream) throws Exception {
    if (stream == null) {
        return null;
    } else {// ww  w .ja  v  a 2 s. com
        ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
        byte buffer[] = new byte[1024];
        int c = 0;
        while ((c = stream.read(buffer)) > 0) {
            byteArray.write(buffer, 0, c);
        }
        byteArray.flush();
        return byteArray.toByteArray();
    }
}

From source file:net.sf.jasperreports.engine.util.JRLoader.java

/**
 *
 *///from  ww  w. j  a  v a2 s  .co m
public static byte[] loadBytes(URL url) throws JRException {
    ByteArrayOutputStream baos = null;
    InputStream is = null;

    try {
        is = url.openStream();
        baos = new ByteArrayOutputStream();

        byte[] bytes = new byte[10000];
        int ln = 0;
        while ((ln = is.read(bytes)) > 0) {
            baos.write(bytes, 0, ln);
        }

        baos.flush();
    } catch (IOException e) {
        throw new JRException(EXCEPTION_MESSAGE_KEY_BYTE_DATA_LOADING_ERROR, new Object[] { url }, e);
    } finally {
        if (baos != null) {
            try {
                baos.close();
            } catch (IOException e) {
            }
        }

        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }

    return baos.toByteArray();
}

From source file:com.heliosapm.tsdblite.json.JSON.java

private static byte[] jserialize(final Serializable ser) {
    if (ser == null)
        return new byte[0];
    ByteArrayOutputStream baos = null;
    ObjectOutputStream oos = null;
    try {/*from  www .j av  a2 s . c o m*/
        baos = new ByteArrayOutputStream(1024);
        oos = new ObjectOutputStream(baos);
        oos.writeObject(ser);
        oos.flush();
        baos.flush();
        return baos.toByteArray();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        if (oos != null)
            try {
                oos.close();
            } catch (Exception x) {
                /* No Op */}
        if (baos != null)
            try {
                baos.close();
            } catch (Exception x) {
                /* No Op */}
    }
}

From source file:net.sf.jasperreports.engine.util.JRLoader.java

/**
 *
 *///  w w w .  j  a  va2s  . c  o  m
public static byte[] loadBytes(File file) throws JRException {
    ByteArrayOutputStream baos = null;
    FileInputStream fis = null;

    try {
        fis = new FileInputStream(file);
        baos = new ByteArrayOutputStream();

        byte[] bytes = new byte[10000];
        int ln = 0;
        while ((ln = fis.read(bytes)) > 0) {
            baos.write(bytes, 0, ln);
        }

        baos.flush();
    } catch (IOException e) {
        throw new JRException(EXCEPTION_MESSAGE_KEY_BYTE_DATA_LOADING_ERROR, new Object[] { file }, e);
    } finally {
        if (baos != null) {
            try {
                baos.close();
            } catch (IOException e) {
            }
        }

        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
            }
        }
    }

    return baos.toByteArray();
}