Example usage for java.io BufferedOutputStream flush

List of usage examples for java.io BufferedOutputStream flush

Introduction

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

Prototype

@Override
public synchronized void flush() throws IOException 

Source Link

Document

Flushes this buffered output stream.

Usage

From source file:it.geosolutions.tools.compress.file.reader.TarReader.java

private static void writeFile(File curr_dest, TarArchiveInputStream tis) throws IOException {
    byte[] buf = new byte[Conf.getBufferSize()];
    FileOutputStream fos = null;//from  w w  w  .j  av a  2  s . c om
    BufferedOutputStream bos_inner = null;
    try {
        fos = new FileOutputStream(curr_dest);
        bos_inner = new BufferedOutputStream(fos, Conf.getBufferSize());
        int read_sz = 0;
        while ((read_sz = tis.read(buf)) != -1) {
            bos_inner.write(buf, 0, read_sz);
            bos_inner.flush();
        }
        //        } catch (IOException e){
    } finally {
        if (bos_inner != null) {
            try {
                bos_inner.close();
            } catch (IOException e) {
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:org.openmrs.module.report.util.FileUtils.java

public static void copyFile(InputStream in, File dest) throws Exception {
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
    byte[] data = new byte[2 * 1024];
    int count;//from  www.  java2  s .  c om
    while ((count = in.read(data, 0, data.length)) != -1) {
        out.write(data, 0, count);
    }
    out.flush();
    out.close();
    in.close();
}

From source file:org.apache.torque.util.VillageUtils.java

/**
 * Converts a hashtable to a byte array for storage/serialization.
 *
 * @param  hash  The Hashtable to convert.
 *
 * @return  A byte[] with the converted Hashtable.
 *
 * @throws  Exception  If an error occurs.
 *//*from ww w . ja v  a  2  s .  c om*/
public static byte[] hashtableToByteArray(final Hashtable hash) throws Exception {
    Hashtable saveData = new Hashtable(hash.size());
    byte[] byteArray = null;

    Iterator keys = hash.entrySet().iterator();
    while (keys.hasNext()) {
        Map.Entry entry = (Map.Entry) keys.next();
        if (entry.getValue() instanceof Serializable) {
            saveData.put(entry.getKey(), entry.getValue());
        }
    }

    ByteArrayOutputStream baos = null;
    BufferedOutputStream bos = null;
    ObjectOutputStream out = null;
    try {
        // These objects are closed in the finally.
        baos = new ByteArrayOutputStream();
        bos = new BufferedOutputStream(baos);
        out = new ObjectOutputStream(bos);

        out.writeObject(saveData);

        out.flush();
        bos.flush();
        baos.flush();
        byteArray = baos.toByteArray();
    } finally {
        close(out);
        close(bos);
        close(baos);
    }
    return byteArray;
}

From source file:org.datavec.api.util.ArchiveUtils.java

/**
 * Extracts files to the specified destination
 * @param file the file to extract to/*from   w  w  w.java  2  s . com*/
 * @param dest the destination directory
 * @throws java.io.IOException
 */
public static void unzipFileTo(String file, String dest) throws IOException {
    File target = new File(file);
    if (!target.exists())
        throw new IllegalArgumentException("Archive doesnt exist");
    FileInputStream fin = new FileInputStream(target);
    int BUFFER = 2048;
    byte data[] = new byte[BUFFER];

    if (file.endsWith(".zip") || file.endsWith(".jar")) {
        //getFromOrigin the zip file content
        ZipInputStream zis = new ZipInputStream(fin);
        //getFromOrigin the zipped file list entry
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {
            String fileName = ze.getName();

            File newFile = new File(dest + File.separator + fileName);

            if (ze.isDirectory()) {
                newFile.mkdirs();
                zis.closeEntry();
                ze = zis.getNextEntry();
                continue;
            }

            log.info("file unzip : " + newFile.getAbsoluteFile());

            //create all non exists folders
            //else you will hit FileNotFoundException for compressed folder

            FileOutputStream fos = new FileOutputStream(newFile);

            int len;
            while ((len = zis.read(data)) > 0) {
                fos.write(data, 0, len);
            }

            fos.flush();
            fos.close();
            zis.closeEntry();
            ze = zis.getNextEntry();
        }

        zis.close();

    }

    else if (file.endsWith(".tar")) {

        BufferedInputStream in = new BufferedInputStream(fin);
        TarArchiveInputStream tarIn = new TarArchiveInputStream(in);

        TarArchiveEntry entry = null;

        /** Read the tar entries using the getNextEntry method **/

        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {

            log.info("Extracting: " + entry.getName());

            /** If the entry is a directory, createComplex the directory. **/

            if (entry.isDirectory()) {

                File f = new File(dest + File.separator + entry.getName());
                f.mkdirs();
            }
            /**
             * If the entry is a file,write the decompressed file to the disk
             * and close destination stream.
             **/
            else {
                int count;

                FileOutputStream fos = new FileOutputStream(dest + File.separator + entry.getName());
                BufferedOutputStream destStream = new BufferedOutputStream(fos, BUFFER);
                while ((count = tarIn.read(data, 0, BUFFER)) != -1) {
                    destStream.write(data, 0, count);
                }

                destStream.flush();
                ;

                IOUtils.closeQuietly(destStream);
            }
        }

        /** Close the input stream **/

        tarIn.close();
    }

    else if (file.endsWith(".tar.gz") || file.endsWith(".tgz")) {

        BufferedInputStream in = new BufferedInputStream(fin);
        GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
        TarArchiveInputStream tarIn = new TarArchiveInputStream(gzIn);

        TarArchiveEntry entry = null;

        /** Read the tar entries using the getNextEntry method **/

        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {

            log.info("Extracting: " + entry.getName());

            /** If the entry is a directory, createComplex the directory. **/

            if (entry.isDirectory()) {

                File f = new File(dest + File.separator + entry.getName());
                f.mkdirs();
            }
            /**
             * If the entry is a file,write the decompressed file to the disk
             * and close destination stream.
             **/
            else {
                int count;

                FileOutputStream fos = new FileOutputStream(dest + File.separator + entry.getName());
                BufferedOutputStream destStream = new BufferedOutputStream(fos, BUFFER);
                while ((count = tarIn.read(data, 0, BUFFER)) != -1) {
                    destStream.write(data, 0, count);
                }

                destStream.flush();

                IOUtils.closeQuietly(destStream);
            }
        }

        /** Close the input stream **/

        tarIn.close();
    }

    else if (file.endsWith(".gz")) {
        GZIPInputStream is2 = new GZIPInputStream(fin);
        File extracted = new File(target.getParent(), target.getName().replace(".gz", ""));
        if (extracted.exists())
            extracted.delete();
        extracted.createNewFile();
        OutputStream fos = FileUtils.openOutputStream(extracted);
        IOUtils.copyLarge(is2, fos);
        is2.close();
        fos.flush();
        fos.close();
    }

}

From source file:org.openmrs.module.report.util.FileUtils.java

public static boolean copyFile(File source, File dest) {
    try {/*  w w  w.  j  a v  a 2  s . c o  m*/
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(source));
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
        byte[] data = new byte[2 * 1024];
        int count;
        while ((count = in.read(data, 0, data.length)) != -1) {
            out.write(data, 0, count);
        }
        out.flush();
        out.close();
        in.close();
        return true;
    } catch (FileNotFoundException e) {
        return false;
    } catch (IOException e) {
        return false;
    }
}

From source file:org.canova.api.util.ArchiveUtils.java

/**
 * Extracts files to the specified destination
 * @param file the file to extract to//from   www . j  ava 2s.c o m
 * @param dest the destination directory
 * @throws java.io.IOException
 */
public static void unzipFileTo(String file, String dest) throws IOException {
    File target = new File(file);
    if (!target.exists())
        throw new IllegalArgumentException("Archive doesnt exist");
    FileInputStream fin = new FileInputStream(target);
    int BUFFER = 2048;
    byte data[] = new byte[BUFFER];

    if (file.endsWith(".zip")) {
        //getFromOrigin the zip file content
        ZipInputStream zis = new ZipInputStream(fin);
        //getFromOrigin the zipped file list entry
        ZipEntry ze = zis.getNextEntry();

        while (ze != null) {
            String fileName = ze.getName();

            File newFile = new File(dest + File.separator + fileName);

            if (ze.isDirectory()) {
                newFile.mkdirs();
                zis.closeEntry();
                ze = zis.getNextEntry();
                continue;
            }

            log.info("file unzip : " + newFile.getAbsoluteFile());

            //create all non exists folders
            //else you will hit FileNotFoundException for compressed folder

            FileOutputStream fos = new FileOutputStream(newFile);

            int len;
            while ((len = zis.read(data)) > 0) {
                fos.write(data, 0, len);
            }

            fos.flush();
            fos.close();
            zis.closeEntry();
            ze = zis.getNextEntry();
        }

        zis.close();

    }

    else if (file.endsWith(".tar")) {

        BufferedInputStream in = new BufferedInputStream(fin);
        TarArchiveInputStream tarIn = new TarArchiveInputStream(in);

        TarArchiveEntry entry = null;

        /** Read the tar entries using the getNextEntry method **/

        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {

            log.info("Extracting: " + entry.getName());

            /** If the entry is a directory, createComplex the directory. **/

            if (entry.isDirectory()) {

                File f = new File(dest + File.separator + entry.getName());
                f.mkdirs();
            }
            /**
             * If the entry is a file,write the decompressed file to the disk
             * and close destination stream.
             **/
            else {
                int count;

                FileOutputStream fos = new FileOutputStream(dest + File.separator + entry.getName());
                BufferedOutputStream destStream = new BufferedOutputStream(fos, BUFFER);
                while ((count = tarIn.read(data, 0, BUFFER)) != -1) {
                    destStream.write(data, 0, count);
                }

                destStream.flush();
                ;

                IOUtils.closeQuietly(destStream);
            }
        }

        /** Close the input stream **/

        tarIn.close();
    }

    else if (file.endsWith(".tar.gz") || file.endsWith(".tgz")) {

        BufferedInputStream in = new BufferedInputStream(fin);
        GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
        TarArchiveInputStream tarIn = new TarArchiveInputStream(gzIn);

        TarArchiveEntry entry = null;

        /** Read the tar entries using the getNextEntry method **/

        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {

            log.info("Extracting: " + entry.getName());

            /** If the entry is a directory, createComplex the directory. **/

            if (entry.isDirectory()) {

                File f = new File(dest + File.separator + entry.getName());
                f.mkdirs();
            }
            /**
             * If the entry is a file,write the decompressed file to the disk
             * and close destination stream.
             **/
            else {
                int count;

                FileOutputStream fos = new FileOutputStream(dest + File.separator + entry.getName());
                BufferedOutputStream destStream = new BufferedOutputStream(fos, BUFFER);
                while ((count = tarIn.read(data, 0, BUFFER)) != -1) {
                    destStream.write(data, 0, count);
                }

                destStream.flush();

                IOUtils.closeQuietly(destStream);
            }
        }

        /** Close the input stream **/

        tarIn.close();
    }

    else if (file.endsWith(".gz")) {
        GZIPInputStream is2 = new GZIPInputStream(fin);
        File extracted = new File(target.getParent(), target.getName().replace(".gz", ""));
        if (extracted.exists())
            extracted.delete();
        extracted.createNewFile();
        OutputStream fos = FileUtils.openOutputStream(extracted);
        IOUtils.copyLarge(is2, fos);
        is2.close();
        fos.flush();
        fos.close();
    }

}

From source file:de.tu_dortmund.ub.data.util.TPUUtil.java

public static String writeResultToFile(final CloseableHttpResponse httpResponse, final Properties config,
        final String exportDataModelID, final String fileEnding) throws IOException, TPUException {

    LOG.info("try to write result to file");

    final String persistInFolderString = config.getProperty(TPUStatics.PERSIST_IN_FOLDER_IDENTIFIER);
    final boolean persistInFolder = Boolean.parseBoolean(persistInFolderString);
    final HttpEntity entity = httpResponse.getEntity();

    final String fileName;

    if (persistInFolder) {

        final InputStream responseStream = entity.getContent();
        final BufferedInputStream bis = new BufferedInputStream(responseStream, 1024);

        final String resultsFolder = config.getProperty(TPUStatics.RESULTS_FOLDER_IDENTIFIER);
        fileName = resultsFolder + File.separatorChar + EXPORT_FILE_NAME_PREFIX + exportDataModelID + DOT
                + fileEnding;/*from   w  w w.  j  ava  2 s . com*/

        LOG.info(String.format("start writing result to file '%s'", fileName));

        final FileOutputStream outputStream = new FileOutputStream(fileName);
        final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);

        IOUtils.copy(bis, bufferedOutputStream);
        bufferedOutputStream.flush();
        outputStream.flush();
        bis.close();
        responseStream.close();
        bufferedOutputStream.close();
        outputStream.close();

        checkResultForError(fileName);
    } else {

        fileName = "[no file name available]";
    }

    EntityUtils.consume(entity);

    return fileName;
}

From source file:org.datavyu.util.NativeLoader.java

/**
 * Unpacks a native application to a temporary location so that it can be
 * utilized from within java code.//from   w w  w .  j a  va  2  s  .c o m
 *
 * @param appJar The jar containing the native app that you want to unpack.
 * @return The path of the native app as unpacked to a temporary location.
 *
 * @throws Exception If unable to unpack the native app to a temporary
 * location.
 */
public static String unpackNativeApp(final String appJar) throws Exception {
    final String nativeLibraryPath;

    if (nativeLibFolder == null) {
        nativeLibraryPath = System.getProperty("java.io.tmpdir") + UUID.randomUUID().toString() + "nativelibs";
        nativeLibFolder = new File(nativeLibraryPath);

        if (!nativeLibFolder.exists()) {
            nativeLibFolder.mkdir();
        }
    }

    // Search the class path for the application jar.
    JarFile jar = null;

    // BugID: 26178921 -- We need to inspect the surefire test class path as
    // well as the regular class path property so that we can scan dependencies
    // during tests.
    String searchPath = System.getProperty("surefire.test.class.path") + File.pathSeparator
            + System.getProperty("java.class.path");

    for (String s : searchPath.split(File.pathSeparator)) {
        // Success! We found a matching jar.
        if (s.endsWith(appJar + ".jar") || s.endsWith(appJar)) {
            jar = new JarFile(s);
        }
    }

    // If we found a jar - it should contain the desired application.
    // decompress as needed.
    if (jar != null) {
        Enumeration<JarEntry> entries = jar.entries();

        while (entries.hasMoreElements()) {
            JarEntry inFile = entries.nextElement();
            File outFile = new File(nativeLibFolder, inFile.getName());

            // If the file from the jar is a directory, create it.
            if (inFile.isDirectory()) {
                outFile.mkdir();

                // The file from the jar is regular - decompress it.
            } else {
                InputStream in = jar.getInputStream(inFile);

                // Create a temporary output location for the library.
                FileOutputStream out = new FileOutputStream(outFile);
                BufferedOutputStream dest = new BufferedOutputStream(out, BUFFER);
                int count;
                byte[] data = new byte[BUFFER];

                while ((count = in.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);
                }

                dest.flush();
                dest.close();
                out.close();
                in.close();
            }

            loadedLibs.add(outFile);
        }

        // Unable to find jar file - abort decompression.
    } else {
        System.err.println("Unable to find jar file for unpacking: " + appJar + ". Java classpath is:");

        for (String s : System.getProperty("java.class.path").split(File.pathSeparator)) {
            System.err.println("    " + s);
        }

        throw new Exception("Unable to find '" + appJar + "' for unpacking.");
    }

    return nativeLibFolder.getAbsolutePath();
}

From source file:com.seleniumtests.util.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();

    try (JarFile jar = new JarFile(location);) {
        logger.info("Extracting jar file::: " + location);
        firefoxProfile.mkdir();/*  w  ww  .ja v a2  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
                try (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:net.sf.jasperreports.engine.xml.JRXmlTemplateWriter.java

/**
 * Writes the XML representation of a template to a file.
 * /*from w  w w  .  j a  v a2s .co m*/
 * @param jasperReportsContext
 * @param template the template
 * @param outputFile the output file name
 * @param encoding the XML encoding to use
 */
public static void writeTemplateToFile(JasperReportsContext jasperReportsContext, JRTemplate template,
        String outputFile, String encoding) {
    BufferedOutputStream fileOut = null;
    boolean close = true;
    try {
        fileOut = new BufferedOutputStream(new FileOutputStream(outputFile));
        writeTemplate(jasperReportsContext, template, fileOut, encoding);

        fileOut.flush();
        close = false;
        fileOut.close();
    } catch (FileNotFoundException e) {
        throw new JRRuntimeException(e);
    } catch (IOException e) {
        throw new JRRuntimeException(e);
    } finally {
        if (fileOut != null && close) {
            try {
                fileOut.close();
            } catch (IOException e) {
                log.warn("Could not close file " + outputFile, e);
            }
        }
    }
}