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:Main.java

/**
 * DOCUMENT ME!/*  w  w  w. j a va  2  s . c  om*/
 *
 * @return DOCUMENT ME!
 *
 * @throws TransformerConfigurationException DOCUMENT ME!
 * @throws TransformerException DOCUMENT ME!
 * @throws Exception DOCUMENT ME!
 */
public static byte[] writeToBytes(Document document)
        throws TransformerConfigurationException, TransformerException, Exception {
    byte[] ret = null;

    TransformerFactory tFactory = TransformerFactory.newInstance();
    tFactory.setAttribute("indent-number", new Integer(4));

    Transformer transformer = tFactory.newTransformer();
    DOMSource source = new DOMSource(document);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    StreamResult result = new StreamResult(bos);
    transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // NOI18N
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // NOI18N
    transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml"); // NOI18N
    transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); // NOI18N

    // indent the output to make it more legible...
    try {
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); // NOI18N
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // NOI18N
    } catch (IllegalArgumentException e) {
        // the JAXP implementation doesn't support indentation, no big deal
        //e.printStackTrace();
    }

    try {
        transformer.transform(source, result);
        ret = bos.toByteArray();
    } finally {
        if (bos != null) {
            bos.flush();
            bos.close();
        }
    }

    return ret;
}

From source file:com.nary.Debug.java

public static Object loadClass(InputStream _inStream, boolean _uncompress) {
    ObjectInputStream ois;//ww w  .  ja  va  2 s .  co  m
    try {
        if (_uncompress) {
            // we need to get the input as a byte [] so we can decompress (inflate) it.  
            Inflater inflater = new Inflater();
            ByteArrayOutputStream bos;
            int bytesAvail = _inStream.available();
            if (bytesAvail > 0) {
                bos = new ByteArrayOutputStream(bytesAvail);
            } else {
                bos = new ByteArrayOutputStream();
            }

            byte[] buffer = new byte[1024];
            int read = _inStream.read(buffer);
            while (read > 0) {
                bos.write(buffer, 0, read);
                read = _inStream.read(buffer);
            }
            bos.flush();
            inflater.setInput(bos.toByteArray());

            bos.reset();
            buffer = new byte[1024];
            int inflated = inflater.inflate(buffer);
            while (inflated > 0) {
                bos.write(buffer, 0, inflated);
                inflated = inflater.inflate(buffer);
            }

            bos.flush();
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());

            ois = new ObjectInputStream(bis);

        } else {
            ois = new ObjectInputStream(_inStream);
        }

        return ois.readObject();
    } catch (Exception E) {
        return null;
    } finally {
        try {
            _inStream.close();
        } catch (Exception ioe) {
        }
    }
}

From source file:com.adaptris.util.ByteArrayDataSourceTest.java

public void testInputStream() throws Exception {
    ByteArrayDataSource bads = new ByteArrayDataSource(EXAMPLE_XML.getBytes(), "text/xml", "name");
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    out.write(bads.getBytes());//ww w.jav  a2s . co m
    out.flush();
    assertEquals("XML", out.toString(), EXAMPLE_XML);
}

From source file:com.discovery.darchrow.io.FileUtil.java

/**
 * ? {@code byte[] bytes}.//from  w ww  .  j a  va 2  s .  c o m
 *
 * @param file
 *            file
 * @return {@link java.io.ByteArrayOutputStream#toByteArray()}
 * @see com.baozun.nebulaplus.io.FileUtil#getFileInputStream(File)
 * @see java.io.ByteArrayOutputStream#toByteArray()
 */
public static final byte[] toByteArray(File file) {
    InputStream inputStream = getFileInputStream(file);

    //Creates a BufferedInputStream and saves its argument, the input stream in, for later use. 
    //An internal buffer array is created and stored in buf.
    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);

    //Creates a new byte array output stream. 
    //The buffer capacity is initially 32 bytes, though its size increases if necessary. 
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    try {
        byte[] bytes = new byte[IOConstants.DEFAULT_BUFFER_LENGTH];
        int j;
        while ((j = bufferedInputStream.read(bytes)) != -1) {
            byteArrayOutputStream.write(bytes, 0, j);
        }
        byteArrayOutputStream.flush();

        byte[] byteArray = byteArrayOutputStream.toByteArray();
        return byteArray;
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        // ???StreamClose.??Close
        IOUtils.closeQuietly(byteArrayOutputStream);
        IOUtils.closeQuietly(bufferedInputStream);
    }
}

From source file:com.couchbase.lite.DatabaseAttachmentTest.java

private static byte[] getBytesFromInputStream(InputStream is) {
    org.apache.commons.io.output.ByteArrayOutputStream os = new org.apache.commons.io.output.ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len = 0;//from  w  w w. j  a v  a  2 s  . c o m
    try {
        while ((len = is.read(buffer)) > 0) {
            os.write(buffer, 0, len);
        }
        os.flush();
    } catch (IOException e) {
        Log.e(Log.TAG, "is.read(buffer) or os.flush() error", e);
        return null;
    }
    return os.toByteArray();
}

From source file:com.daniel.processimage.ImageManager.java

public byte[] readImage(Part file) throws FileNotFoundException, IOException {
    InputStream is = file.getInputStream();
    BufferedImage bufferedImage = ImageIO.read(is);
    ByteArrayOutputStream byteMas = new ByteArrayOutputStream();
    ImageIO.write(bufferedImage, "png", byteMas);
    byteMas.flush();
    byte[] imageInBytes = byteMas.toByteArray();
    byteMas.close();//from  w w w .  j  ava  2 s  .c  om

    return imageInBytes;
}

From source file:com.aimluck.eip.fileupload.util.FileuploadUtils.java

/**
 * //from  ww w  . j  a  v a  2s .  c  o m
 * @param org_id
 * @param folderName
 * @param uid
 * @param fileBean
 * @param acceptExts
 *          String[] ext = { ".jpg", ".jpeg" };
 * @param msgList
 * @return
 */
public static byte[] getBytesFilebean(String org_id, String folderName, int uid, FileuploadLiteBean fileBean,
        String[] acceptExts, List<String> msgList) {
    byte[] result = null;
    try {

        String file_name = fileBean.getFileName();

        if (acceptExts != null && acceptExts.length > 0) {
            // ???
            // ????
            boolean isAccept = false;
            String tmpExt = null;
            int len = acceptExts.length;
            for (int i = 0; i < len; i++) {
                if (!acceptExts[i].startsWith(".")) {
                    tmpExt = "." + acceptExts[i];
                }
                if (file_name.toLowerCase().endsWith(tmpExt)) {
                    isAccept = true;
                }
            }
            if (!isAccept) {
                // ???????null ?
                return null;
            }
        }

        InputStream is = null;
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {
            is = ALStorageService.getFile(FOLDER_TMP_FOR_ATTACHMENT_FILES,
                    uid + ALStorageService.separator() + folderName, file_name);
            byte b[] = new byte[512];
            int len = -1;
            while ((len = is.read(b, 0, b.length)) != -1) {
                output.write(b, 0, len);
            }
            output.flush();
        } finally {
            if (is != null) {
                is.close();
            }
        }

        result = output.toByteArray();
    } catch (Exception e) {
        logger.error("fileupload", e);
        return null;
    }
    return result;
}

From source file:de.bps.onyx.util.SummaryCheckSumValidator.java

/**
 * Validates the Onyx test result summary pages checksum.
 * //  www .j  a  va  2s.co m
 * @param file
 *            The file containing the summary HTML
 * @return SummaryChecksumValidatorResult structure. The contained validated
 *         field contains the validation result.
 * 
 * @see SummaryChecksumValidatorResult
 */
public static SummaryChecksumValidatorResult validate(final File file) {
    FileInputStream fis = null;
    final ByteArrayOutputStream baos = new ByteArrayOutputStream((int) file.length());
    try {
        fis = new FileInputStream(file);
        final byte[] buf = new byte[102400];
        int read = 0;
        while ((read = fis.read(buf)) >= 0) {
            baos.write(buf, 0, read);
        }
    } catch (final IOException e) {
        //         log.error("Error reading file to validate: " + file.getAbsolutePath(), e);
        final SummaryChecksumValidatorResult result = new SummaryChecksumValidatorResult();
        result.result = "onyx.summary.validation.result.error.reading.file";
        result.info = file.getAbsolutePath() + " - " + e.getMessage();
        return result;

    } finally {
        try {
            if (fis != null) {
                fis.close();
                fis = null;
            }
        } catch (final Exception e) {
            // ignore
        }
    }

    try {
        baos.flush();
    } catch (final IOException e) {
        // ignore
    }

    final String html = baos.toString();

    try {
        baos.close();
    } catch (final IOException e) {
        // ignore
    }

    return internalValidate(html);
}

From source file:cz.cvut.fel.integracniportal.extension.SftpChannel.java

public InputStream getFile(String filename) throws SftpException, IOException {
    InputStream inputStream = sftpChannel.get(filename);
    ByteArrayOutputStream clonedStream = new ByteArrayOutputStream();
    IOUtils.copy(inputStream, clonedStream);
    clonedStream.flush();
    InputStream result = new ByteArrayInputStream(clonedStream.toByteArray());
    sftpChannel.disconnect();/*w w  w .ja  v a2s. c om*/
    return result;
}

From source file:net.sourceforge.floggy.persistence.pool.DirectoryOutputPool.java

private void write(InputStream in, File file) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOUtils.copy(in, baos);/*from w  w  w  .j  a v  a 2 s .co m*/
    baos.flush();

    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    FileOutputStream out = new FileOutputStream(file);
    IOUtils.copy(bais, out);
    out.flush();
    out.close();
    in.close();
}