Example usage for java.io ByteArrayOutputStream close

List of usage examples for java.io ByteArrayOutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closing a ByteArrayOutputStream has no effect.

Usage

From source file:com.netsteadfast.greenstep.util.SimpleUtils.java

/**
 * Encode image to string// w w w. j  a  v  a2  s. c  om
 * @param image The image to encode
 * @param type jpeg, bmp, ...
 * @return encoded string
 */
public static String encodeToString(BufferedImage image, String type) {
    String imageString = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        ImageIO.write(image, type, bos);
        byte[] imageBytes = bos.toByteArray();
        imageString = DatatypeConverter.printBase64Binary(imageBytes);
        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return imageString;
}

From source file:com.stacksync.desktop.util.FileUtil.java

public static byte[] gzip(byte[] content) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
    gzipOutputStream.write(content);//w  w  w. java 2  s  .c om
    gzipOutputStream.close();

    byte[] result = byteArrayOutputStream.toByteArray();
    byteArrayOutputStream.close();

    return result;
}

From source file:fr.gael.dhus.datastore.processing.ProcessingUtils.java

public static List<MetadataIndex> getIndexesFrom(URL url) {
    java.util.Collection<String> properties = null;
    DrbNode node = null;//from   w  ww .ja va2 s. c o  m
    DrbCortexItemClass cl = null;

    // Prepare the index structure.
    List<MetadataIndex> indexes = new ArrayList<MetadataIndex>();

    // Prepare the DRb node to be processed
    try {
        // First : force loading the model before accessing items.
        node = ProcessingUtils.getNodeFromPath(url.getPath());
        cl = ProcessingUtils.getClassFromNode(node);
        logger.info("Class \"" + cl.getLabel() + "\" for product " + node.getName());

        // Get all values of the metadata properties attached to the item
        // class or any of its super-classes
        properties = cl.listPropertyStrings(METADATA_NAMESPACE + PROPERTY_METADATA_EXTRACTOR, false);

        // Return immediately if no property value were found
        if (properties == null) {
            logger.warn("Item \"" + cl.getLabel() + "\" has no metadata defined.");
            return null;
        }
    } catch (IOException e) {
        throw new UnsupportedOperationException("Error While decoding drb node", e);
    }

    // Loop among retrieved property values
    for (String property : properties) {
        // Filter possible XML markup brackets that could have been encoded
        // in a CDATA section
        property = property.replaceAll("&lt;", "<");
        property = property.replaceAll("&gt;", ">");
        /*
         * property = property.replaceAll("\n", " "); // Replace eol by blank
         * space property = property.replaceAll(" +", " "); // Remove
         * contiguous blank spaces
         */

        // Create a query for the current metadata extractor
        Query metadataQuery = new Query(property);

        // Evaluate the XQuery
        DrbSequence metadataSequence = metadataQuery.evaluate(node);

        // Check that something results from the evaluation: jump to next
        // value otherwise
        if ((metadataSequence == null) || (metadataSequence.getLength() < 1)) {
            continue;
        }

        // Loop among results
        for (int iitem = 0; iitem < metadataSequence.getLength(); iitem++) {
            // Get current metadata node
            DrbNode n = (DrbNode) metadataSequence.getItem(iitem);

            // Get name
            DrbAttribute name_att = n.getAttribute("name");
            Value name_v = null;
            if (name_att != null)
                name_v = name_att.getValue();
            String name = null;
            if (name_v != null)
                name = name_v.convertTo(Value.STRING_ID).toString();

            // get type
            DrbAttribute type_att = n.getAttribute("type");
            Value type_v = null;
            if (type_att != null)
                type_v = type_att.getValue();
            else
                type_v = new fr.gael.drb.value.String(MIME_PLAIN_TEXT);
            String type = type_v.convertTo(Value.STRING_ID).toString();

            // get category
            DrbAttribute cat_att = n.getAttribute("category");
            Value cat_v = null;
            if (cat_att != null)
                cat_v = cat_att.getValue();
            else
                cat_v = new fr.gael.drb.value.String("product");
            String category = cat_v.convertTo(Value.STRING_ID).toString();

            // get category
            DrbAttribute qry_att = n.getAttribute("queryable");
            String queryable = null;
            if (qry_att != null) {
                Value qry_v = qry_att.getValue();
                if (qry_v != null)
                    queryable = qry_v.convertTo(Value.STRING_ID).toString();
            }

            // Get value
            String value = null;
            if (MIME_APPLICATION_GML.equals(type) && n.hasChild()) {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                XmlWriter.writeXML(n.getFirstChild(), out);
                value = out.toString();
                try {
                    out.close();
                } catch (IOException e) {
                    logger.warn("Cannot close stream !", e);
                }
            } else
            // Case of "text/plain"
            {
                Value value_v = n.getValue();
                if (value_v != null) {
                    value = value_v.convertTo(Value.STRING_ID).toString();
                    value = value.trim();
                }
            }

            if ((name != null) && (value != null)) {
                MetadataIndex index = new MetadataIndex();
                index.setName(name);
                try {
                    index.setType(new MimeType(type).toString());
                } catch (MimeTypeParseException e) {
                    logger.warn("Wrong metatdata extractor mime type in class \"" + cl.getLabel()
                            + "\" for metadata called \"" + name + "\".", e);
                }
                index.setCategory(category);
                index.setValue(value);
                index.setQueryable(queryable);
                indexes.add(index);
            } else {
                String field_name = "";
                if (name != null)
                    field_name = name;
                else if (queryable != null)
                    field_name = queryable;
                else if (category != null)
                    field_name = "of category " + category;

                logger.warn("Nothing extracted for field " + field_name);
            }
        }
    }
    return indexes;
}

From source file:com.iStudy.Study.Renren.Util.java

public static byte[] getBytes(String url, Bundle params) {
    try {// w ww . j  ava  2  s. c  o  m
        HttpURLConnection conn = openConn(url, "post", params);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        InputStream is = conn.getInputStream();
        for (int i = 0; (i = is.read(buf)) > 0;) {
            os.write(buf, 0, i);
        }
        is.close();
        os.close();
        return os.toByteArray();
    } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage());
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.nloko.android.Utils.java

public static byte[] getByteArrayFromInputStream(InputStream is) {
    if (is == null) {
        throw new IllegalArgumentException("is");
    }//from www  . ja v  a 2s .c om

    int size = 8192;
    int read = 0;
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(size);
    byte[] buffer = new byte[size];
    byte[] array = null;

    try {
        while ((read = is.read(buffer, 0, buffer.length)) > 0) {
            bytes.write(buffer, 0, read);
        }
    } catch (IOException ex) {
        return null;
    } finally {
        try {
            if (bytes != null) {
                array = bytes.toByteArray();
                bytes.close();
            }
        } catch (IOException e) {
        }
    }

    return array;
}

From source file:es.sm2.openppm.core.plugin.action.GenericAction.java

/**
 *
 * @param files/*from  www .j  av a2 s.  com*/
 * @return
 * @throws IOException
 */
public static byte[] zipFiles(List<File> files) throws IOException {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);

    for (File f : files) {

        zos.putNextEntry(new ZipEntry(f.getName()));

        zos.write(getBytesFromFile(f.getAbsoluteFile()));

        zos.closeEntry();
    }

    zos.flush();
    baos.flush();
    zos.close();
    baos.close();

    return baos.toByteArray();
}

From source file:com.ah.ui.actions.config.OnBoardUISettingAction.java

public static byte[] file2ByteArray(File inFile) {
    byte[] ret = null;
    InputStream in = null;//from  ww w  .  ja  v  a2s. co  m
    try {
        in = new FileInputStream(inFile);

        byte[] buffer = new byte[1024];
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int readSize = 0;
        try {
            while ((readSize = in.read(buffer)) >= 0) {
                out.write(buffer, 0, readSize);
            }
            ret = out.toByteArray();
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
            try {
                out.close();
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage());
    }
    return ret;
}

From source file:net.naijatek.myalumni.util.utilities.FileUtil.java

public static byte[] getBytes(final InputStream inputStream) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
    byte[] block = new byte[512];
    while (true) {
        int readLength = inputStream.read(block);
        if (readLength == -1) {
            break; // end of file
        }/*ww  w.  j a v a  2s . c om*/
        byteArrayOutputStream.write(block, 0, readLength);
    }
    byte[] retValue = byteArrayOutputStream.toByteArray();
    byteArrayOutputStream.close();
    return retValue;
}

From source file:outfox.dict.contest.util.FileUtils.java

/**
 * ??/*w w  w  . java2 s.  c o  m*/
 * @param downloadUrl
 * @return
 */
public static byte[] getbytesFromURL(String downloadUrl) {
    HttpURLConnection httpUrl = null;
    ByteArrayOutputStream out = null;
    byte[] byteArray = null;
    InputStream in = null;
    try {
        // 
        URL url = new URL(downloadUrl);
        httpUrl = (HttpURLConnection) url.openConnection();
        // ?
        httpUrl.connect();
        // ??
        in = httpUrl.getInputStream();

        out = new ByteArrayOutputStream();
        byte[] b = new byte[4096];
        int n;
        while ((n = in.read(b)) != -1) {
            out.write(b, 0, n);
        }
        byteArray = out.toByteArray();
        in.close();
        out.close();
        httpUrl.disconnect();
    } catch (Exception e) {
        LOG.error("FileUtils.getBytesFromURL error...", e);
    }
    return byteArray;
}

From source file:ZipUtil.java

/**
 * Inflates a previously deflated file.//from   w  w w.  j a v a  2  s . c  om
 */
public static byte[] unzipByteArray(byte[] file) throws IOException {
    byte[] byReturn = null;

    Inflater oInflate = new Inflater(false);
    oInflate.setInput(file);

    ByteArrayOutputStream oZipStream = new ByteArrayOutputStream();
    try {
        while (!oInflate.finished()) {
            byte[] byRead = new byte[ZIP_BUFFER_SIZE];
            int iBytesRead = oInflate.inflate(byRead);
            if (iBytesRead == byRead.length) {
                oZipStream.write(byRead);
            } else {
                oZipStream.write(byRead, 0, iBytesRead);
            }
        }
        byReturn = oZipStream.toByteArray();
    } catch (DataFormatException ex) {
        throw new IOException("Attempting to unzip file that is not zipped.");
    } finally {
        oZipStream.close();
    }
    return byReturn;
}