Example usage for java.io BufferedOutputStream BufferedOutputStream

List of usage examples for java.io BufferedOutputStream BufferedOutputStream

Introduction

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

Prototype

public BufferedOutputStream(OutputStream out, int size) 

Source Link

Document

Creates a new buffered output stream to write data to the specified underlying output stream with the specified buffer size.

Usage

From source file:adams.core.io.Bzip2Utils.java

/**
 * Decompresses the specified archive.//from   ww w. j  a v a  2s  .  c  om
 * <br><br>
 * See <a href="https://commons.apache.org/compress/examples.html" target="_blank">Apache commons/compress</a>.
 *
 * @param archiveFile   the archive file to decompress
 * @param buffer   the buffer size to use
 * @param outputFile   the destination file
 * @return      the error message, null if everything OK
 */
public static String decompress(File archiveFile, int buffer, File outputFile) {
    String result;
    byte[] buf;
    int len;
    FileInputStream fis;
    BZip2CompressorInputStream in;
    BufferedOutputStream out;
    String msg;

    in = null;
    out = null;
    fis = null;
    result = null;
    try {
        // does file already exist?
        if (outputFile.exists())
            System.err.println("WARNING: overwriting '" + outputFile + "'!");

        // create GZIP file
        buf = new byte[buffer];
        fis = new FileInputStream(archiveFile.getAbsolutePath());
        in = new BZip2CompressorInputStream(new BufferedInputStream(fis));
        out = new BufferedOutputStream(new FileOutputStream(outputFile), buffer);

        // Transfer bytes from the file to the GZIP file
        while ((len = in.read(buf)) > 0)
            out.write(buf, 0, len);
    } catch (Exception e) {
        msg = "Failed to decompress '" + archiveFile + "': ";
        System.err.println(msg);
        e.printStackTrace();
        result = msg + e;
    } finally {
        FileUtils.closeQuietly(fis);
        FileUtils.closeQuietly(in);
        FileUtils.closeQuietly(out);
    }

    return result;
}

From source file:com.frostwire.android.gui.util.DiskLruRawDataCache.java

private boolean writeBytesToFile(byte[] data, DiskLruCache.Editor editor)
        throws IOException, FileNotFoundException {
    OutputStream out = null;//from   w ww . j a  va2  s .co m
    try {
        out = new BufferedOutputStream(editor.newOutputStream(0), IO_BUFFER_SIZE);
        return IOUtils.copy(new ByteArrayInputStream(data), out) > 0;
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.googlecode.jsfFlex.shared.tasks.sdk.UnzipTask.java

protected void performTask() {

    BufferedOutputStream bufferOutputStream = null;
    ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(_file));
    ZipEntry entry;//from w  w w  .  j a  v a2s.co m

    try {

        while ((entry = zipInputStream.getNextEntry()) != null) {

            ensureDirectoryExists(entry.getName(), entry.isDirectory());

            bufferOutputStream = new BufferedOutputStream(new FileOutputStream(_dest + entry.getName()),
                    BUFFER_SIZE);
            int currRead = 0;
            byte[] dataRead = new byte[BUFFER_SIZE];

            while ((currRead = zipInputStream.read(dataRead, 0, BUFFER_SIZE)) != -1) {
                bufferOutputStream.write(dataRead, 0, currRead);
            }
            bufferOutputStream.flush();
            bufferOutputStream.close();
        }

        _log.debug("UnzipTask performTask has been completed with " + toString());
    } catch (IOException ioExcept) {
        StringBuilder errorMessage = new StringBuilder();
        errorMessage.append("Error in Unzip's performTask with following fields \n");
        errorMessage.append(toString());
        throw new ComponentBuildException(errorMessage.toString(), ioExcept);
    } finally {
        try {
            zipInputStream.close();
            if (bufferOutputStream != null) {
                bufferOutputStream.close();
            }
        } catch (IOException innerIOExcept) {
            _log.info("Error while closing the streams within UnzipTask's finally block");
        }
    }

}

From source file:com.freedomotic.util.Unzip.java

/**
 *
 * @param zipFile//w  w w. j a  va  2  s .  c  o m
 * @throws ZipException
 * @throws IOException
 */
public static void unzip(String zipFile) throws IOException {

    if (StringUtils.isEmpty(zipFile)) {
        LOG.error("File path not provided, no unzipping performed");
        return;
    }

    File file = new File(zipFile);

    if (!file.exists()) {
        LOG.error("File not existing, no unzipping performed");
        return;
    }

    try (ZipFile zip = new ZipFile(file);) {
        String newPath = zipFile.substring(0, zipFile.length() - 4);
        //simulates the unzip here feature
        newPath = newPath.substring(0, newPath.lastIndexOf(File.separator));

        Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();

        // Process each entry
        while (zipFileEntries.hasMoreElements()) {
            // grab a zip file entry
            ZipEntry entry = zipFileEntries.nextElement();
            String currentEntry = entry.getName();
            File destFile = new File(newPath, currentEntry);
            File destinationParent = destFile.getParentFile();

            // create the parent directory structure if needed
            destinationParent.mkdirs();

            if (!entry.isDirectory()) {
                try (BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
                        FileOutputStream fos = new FileOutputStream(destFile);
                        BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);) {

                    int currentByte;

                    // establish buffer for writing file
                    byte[] data = new byte[BUFFER];

                    // read and write until last byte is encountered
                    while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                        dest.write(data, 0, currentByte);
                    }
                } catch (IOException ex) {
                    LOG.error(Freedomotic.getStackTraceInfo(ex));
                }
            }

            if (currentEntry.endsWith(".zip")) {
                // found a zip file, try to open
                unzip(destFile.getAbsolutePath());
            }
        }
    }
}

From source file:org.trustedanalytics.servicebroker.gearpump.service.file.FileWriterService.java

private void writeData(InputStream inputStream) throws IOException {
    int count;//w w  w.  j av  a  2 s. co m
    byte[] data = new byte[BUFFER];
    OutputStream fos = fileWriter.getOutputStream();
    try (BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
        while ((count = inputStream.read(data, 0, BUFFER)) != -1) {
            dest.write(data, 0, count);
        }
    }
}

From source file:edu.caltech.ipac.firefly.server.network.HttpServices.java

public static int getDataViaUrl(URL url, File results) throws FileNotFoundException {
    return getDataViaUrl(url, new BufferedOutputStream(new FileOutputStream(results), FileUtil.BUFFER_SIZE));
}

From source file:com.elastica.helper.FileUtility.java

public static void extractJar(final String storeLocation, final Class<?> clz) throws IOException {
    File firefoxProfile = new File(storeLocation);
    String location = clz.getProtectionDomain().getCodeSource().getLocation().getFile();

    JarFile jar = new JarFile(location);
    System.out.println("Extracting jar file::: " + location);
    firefoxProfile.mkdir();//from   ww  w . j a v a  2 s .c  o m

    Enumeration<?> jarFiles = jar.entries();
    while (jarFiles.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) jarFiles.nextElement();
        String currentEntry = entry.getName();
        File destinationFile = new File(storeLocation, currentEntry);
        File destinationParent = destinationFile.getParentFile();

        // create the parent directory structure if required
        destinationParent.mkdirs();
        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(jar.getInputStream(entry));
            int currentByte;

            // buffer for writing file
            byte[] data = new byte[BUFFER];

            // write the current file to disk
            FileOutputStream fos = new FileOutputStream(destinationFile);
            BufferedOutputStream destination = new BufferedOutputStream(fos, BUFFER);

            // read and write till last byte
            while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                destination.write(data, 0, currentByte);
            }

            destination.flush();
            destination.close();
            is.close();
        }
    }

    FileUtils.deleteDirectory(new File(storeLocation + "\\META-INF"));
    if (OSUtility.isWindows()) {
        new File(storeLocation + "\\" + clz.getCanonicalName().replaceAll("\\.", "\\\\") + ".class").delete();
    } else {
        new File(storeLocation + "/" + clz.getCanonicalName().replaceAll("\\.", "/") + ".class").delete();
    }
}

From source file:Main.java

public static boolean unzip(InputStream inputStream, String dest, boolean replaceIfExists) {

    final int BUFFER_SIZE = 4096;

    BufferedOutputStream bufferedOutputStream = null;

    boolean succeed = true;

    try {/*from   ww  w.  j  a v  a 2  s . c o m*/
        ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream));
        ZipEntry zipEntry;

        while ((zipEntry = zipInputStream.getNextEntry()) != null) {

            String zipEntryName = zipEntry.getName();

            //             if(!zipEntry.isDirectory()) {
            //                 File fil = new File(dest + zipEntryName);
            //                 fil.getParent()
            //             }

            // file exists ? delete ?
            File file2 = new File(dest + zipEntryName);

            if (file2.exists()) {
                if (replaceIfExists) {

                    try {
                        boolean b = deleteDir(file2);
                        if (!b) {
                            Log.e("Haggle", "Unzip failed to delete " + dest + zipEntryName);
                        } else {
                            Log.d("Haggle", "Unzip deleted " + dest + zipEntryName);
                        }
                    } catch (Exception e) {
                        Log.e("Haggle", "Unzip failed to delete " + dest + zipEntryName, e);
                    }
                }
            }

            // extract
            File file = new File(dest + zipEntryName);

            if (file.exists()) {

            } else {
                if (zipEntry.isDirectory()) {
                    file.mkdirs();
                    chmod(file, 0755);

                } else {

                    // create parent file folder if not exists yet
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                        chmod(file.getParentFile(), 0755);
                    }

                    byte buffer[] = new byte[BUFFER_SIZE];
                    bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file), BUFFER_SIZE);
                    int count;

                    while ((count = zipInputStream.read(buffer, 0, BUFFER_SIZE)) != -1) {
                        bufferedOutputStream.write(buffer, 0, count);
                    }

                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
                }
            }

            // enable standalone python
            if (file.getName().endsWith(".so") || file.getName().endsWith(".xml")
                    || file.getName().endsWith(".py") || file.getName().endsWith(".pyc")
                    || file.getName().endsWith(".pyo")) {
                chmod(file, 0755);
            }

            Log.d("Haggle", "Unzip extracted " + dest + zipEntryName);
        }

        zipInputStream.close();

    } catch (FileNotFoundException e) {
        Log.e("Haggle", "Unzip error, file not found", e);
        succeed = false;
    } catch (Exception e) {
        Log.e("Haggle", "Unzip error: ", e);
        succeed = false;
    }

    return succeed;
}