Example usage for java.io BufferedOutputStream write

List of usage examples for java.io BufferedOutputStream write

Introduction

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

Prototype

@Override
public synchronized void write(byte b[], int off, int len) throws IOException 

Source Link

Document

Writes len bytes from the specified byte array starting at offset off to this buffered output stream.

Usage

From source file:com.stevpet.sonar.plugins.dotnet.mscover.codecoverage.command.ZipUtils.java

/**
 * Extracts the specified folder from the specified archive, into the supplied output directory.
 * /*from   w  w w  . jav  a 2  s  .com*/
 * @param archivePath
 *          the archive Path
 * @param folderToExtract
 *          the folder to extract
 * @param outputDirectory
 *          the output directory
 * @return the extracted folder path
 * @throws IOException
 *           if a problem occurs while extracting
 */
public static File extractArchiveFolderIntoDirectory(String archivePath, String folderToExtract,
        String outputDirectory) throws IOException {
    File destinationFolder = new File(outputDirectory);
    destinationFolder.mkdirs();

    ZipFile zip = null;
    try {
        zip = new ZipFile(new File(archivePath));
        Enumeration<?> zipFileEntries = zip.entries();
        // Process each entry
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();
            if (currentEntry.startsWith(folderToExtract)) {
                File destFile = new File(destinationFolder, currentEntry);
                destFile.getParentFile().mkdirs();
                if (!entry.isDirectory()) {
                    BufferedInputStream is = null;
                    BufferedOutputStream dest = null;
                    try {
                        is = new BufferedInputStream(zip.getInputStream(entry));
                        int currentByte;
                        // establish buffer for writing file
                        byte data[] = new byte[BUFFER_SIZE];

                        // write the current file to disk
                        FileOutputStream fos = new FileOutputStream(destFile);
                        dest = new BufferedOutputStream(fos, BUFFER_SIZE);

                        // read and write until last byte is encountered
                        while ((currentByte = is.read(data, 0, BUFFER_SIZE)) != -1) {
                            dest.write(data, 0, currentByte);
                        }
                    } finally {
                        if (dest != null) {
                            dest.flush();
                        }
                        IOUtils.closeQuietly(dest);
                        IOUtils.closeQuietly(is);
                    }
                }
            }
        }
    } finally {
        if (zip != null) {
            zip.close();
        }
    }

    return new File(destinationFolder, folderToExtract);
}

From source file:com.eviware.soapui.integration.exporter.ProjectExporter.java

public static void unpackageAll(String archive, String path) {
    try {//  w  w w. ja v a  2 s.c o  m
        BufferedOutputStream dest = null;
        FileInputStream fis = new FileInputStream(archive);
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            int count;
            byte data[] = new byte[BUFFER];
            // write the files to the disk
            FileOutputStream fos = new FileOutputStream(path + File.separator + entry.getName());
            dest = new BufferedOutputStream(fos, BUFFER);
            while ((count = zis.read(data, 0, BUFFER)) != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
            dest.close();
        }
        zis.close();
    } catch (Exception e) {
        SoapUI.logError(e);
    }
}

From source file:com.eurotong.orderhelperandroid.Common.java

@TargetApi(9)
public static void downloadFile(String fileName) {
    try {/*from  ww w  .  j a va  2  s . c om*/
        //http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy);

        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
        Date date = new Date();
        String datetime = dateFormat.format(date);
        // Create a URL for the desired page          
        URL url = new URL(
                Common.GetBaseUrl() + Customer.Current().CustomerID + "/" + fileName + "?d=" + datetime);

        // Read all the text returned by the server  

        BufferedInputStream in = new BufferedInputStream(url.openStream());

        //http://stackoverflow.com/questions/4228699/write-and-read-strings-to-from-internal-file
        FileOutputStream fos = MyApplication.getAppContext().openFileOutput(fileName, Context.MODE_PRIVATE);
        /*
        DataOutputStream out = 
            new DataOutputStream(fos);
                
        String str;
        while ((str = in.readLine()) != null) {
        // str is one line of text; readLine() strips the newline character(s)
           Log.i(Define.APP_CATALOG, str);
           out.writeUTF(str);
        }
        */
        BufferedOutputStream out = new BufferedOutputStream(fos, 4096);
        byte[] data = new byte[4096];
        int bytesRead = 0, totalRead = 0;
        while ((bytesRead = in.read(data, 0, data.length)) >= 0) {
            out.write(data, 0, bytesRead);

            // update progress bar
            totalRead += bytesRead;
            /*
            int totalReadInKB = totalRead / 1024;
            msg = Message.obtain(parentActivity.activityHandler,
                            AndroidFileDownloader.MESSAGE_UPDATE_PROGRESS_BAR,
                            totalReadInKB, 0);
            parentActivity.activityHandler.sendMessage(msg);
            */
        }

        in.close();
        //fos.close();
        out.close();

        Toast.makeText(MyApplication.getAppContext(),
                fileName + MyApplication.getAppContext().getString(R.string.msg_download_file_finished),
                Toast.LENGTH_LONG).show();

        try {
            if (fileName.equals(Define.MENU_FILE_NAME)) {
                Product.ParseMenuList(Common.GetFileInputStreamFromStorage(fileName));
                Log.i(Define.APP_CATALOG, "menus size:" + "");
                Product.Reload();
            } else if (fileName.equals(Define.PRINT_LAYOUT_NAME)) {
                PrintLayout bi = PrintLayout
                        .Parse(Common.GetFileInputStreamFromStorage(Define.PRINT_LAYOUT_NAME));
                Log.i(Define.APP_CATALOG, Define.PRINT_LAYOUT_NAME);
                PrintLayout.Reload();
            } else if (fileName.equals(Define.BUSINESS_INFO_FILE_NAME)) {
                BusinessInfo bi = BusinessInfo
                        .Parse(Common.GetFileInputStreamFromStorage(Define.BUSINESS_INFO_FILE_NAME));
                Log.i(Define.APP_CATALOG, "setting: businessname:" + bi.getBusinessName());
                BusinessInfo.Reload();
            } else if (fileName.equals(Define.SETTING_FILE_NAME)) {
                Setting setting = Setting.Parse(Common.GetFileInputStreamFromStorage(Define.SETTING_FILE_NAME));
                Log.i(Define.APP_CATALOG, "setting: printer port" + setting.getPrinterPort());
                setting.Reload();
            } else if (fileName.equals(Define.PRINT_LAYOUT_BAR_NAME)) {
                PrintLayout bi = PrintLayout
                        .Parse(Common.GetFileInputStreamFromStorage(Define.PRINT_LAYOUT_BAR_NAME));
                Log.i(Define.APP_CATALOG, Define.PRINT_LAYOUT_BAR_NAME);
                PrintLayout.Reload();
            }

            else if (fileName.equals(Define.PRINT_LAYOUT_KITCHEN_NAME)) {
                PrintLayout bi = PrintLayout
                        .Parse(Common.GetFileInputStreamFromStorage(Define.PRINT_LAYOUT_KITCHEN_NAME));
                Log.i(Define.APP_CATALOG, Define.PRINT_LAYOUT_KITCHEN_NAME);
                PrintLayout.Reload();
            } else if (fileName.equals(Define.DEVICE_FILE)) {
                Device bi = Device.Parse(Common.GetFileInputStreamFromStorage(Define.DEVICE_FILE));
                Log.i(Define.APP_CATALOG, Define.DEVICE_FILE);
                Device.Reload();
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (MalformedURLException e) {
        Log.e(Define.APP_CATALOG, e.toString());
    } catch (IOException e) {
        Toast.makeText(MyApplication.getAppContext(),
                fileName + MyApplication.getAppContext().getString(R.string.msg_download_error),
                Toast.LENGTH_LONG).show();
        Log.e(Define.APP_CATALOG, e.toString());
        e.printStackTrace();
    } catch (Exception e) {
        Toast.makeText(MyApplication.getAppContext(),
                fileName + MyApplication.getAppContext().getString(R.string.msg_download_error),
                Toast.LENGTH_LONG).show();
        Log.e(Define.APP_CATALOG, e.toString());
    }
}

From source file:eionet.gdem.utils.ZipUtil.java

/**
 * Unzips files to output directory.//from  w ww.j  av  a  2s.c o  m
 * @param inZip Zip file
 * @param outDir Output directory
 * @throws IOException If an error occurs.
 */
public static void unzip(String inZip, String outDir) throws IOException {

    File sourceZipFile = new File(inZip);
    File unzipDestinationDirectory = new File(outDir);

    // Open Zip file for reading
    ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);

    // Create an enumeration of the entries in the zip file
    Enumeration zipFileEntries = zipFile.entries();

    // Process each entry
    while (zipFileEntries.hasMoreElements()) {
        // grab a zip file entry
        ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();

        String currentEntry = entry.getName();
        // System.out.println("Extracting: " + entry);

        File destFile = new File(unzipDestinationDirectory, currentEntry);

        // grab file's parent directory structure
        File destinationParent = destFile.getParentFile();

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

        // extract file if not a directory
        if (!entry.isDirectory()) {
            BufferedInputStream is = null;
            BufferedOutputStream dest = null;
            try {
                is = new BufferedInputStream(zipFile.getInputStream(entry));
                int currentByte;
                // establish buffer for writing file
                byte[] data = new byte[BUFFER];

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

                // read and write until last byte is encountered
                while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, currentByte);
                }
            } finally {
                IOUtils.closeQuietly(dest);
                IOUtils.closeQuietly(is);
            }
        }
    }
    zipFile.close();
}

From source file:com.glaf.core.util.FileUtils.java

public static void save(String filename, InputStream inputStream) {
    if (filename == null || inputStream == null) {
        return;/*from w  ww  .  jav  a2s  .  c  om*/
    }
    String path = "";
    String sp = System.getProperty("file.separator");
    if (filename.indexOf(sp) != -1) {
        path = filename.substring(0, filename.lastIndexOf(sp));
    }
    if (filename.indexOf("/") != -1) {
        path = filename.substring(0, filename.lastIndexOf("/"));
    }
    path = getJavaFileSystemPath(path);
    java.io.File dir = new java.io.File(path + sp);
    mkdirsWithExistsCheck(dir);
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        bis = new BufferedInputStream(inputStream);
        bos = new BufferedOutputStream(new FileOutputStream(filename));
        int bytesRead = 0;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((bytesRead = bis.read(buffer, 0, BUFFER_SIZE)) != -1) {
            bos.write(buffer, 0, bytesRead);
        }
        bos.flush();
        bis.close();
        bos.close();
        bis = null;
        bos = null;
    } catch (IOException ex) {
        bis = null;
        bos = null;
        throw new RuntimeException(ex);
    } finally {
        try {
            if (bis != null) {
                bis.close();
                bis = null;
            }
            if (bos != null) {
                bos.close();
                bos = null;
            }
        } catch (IOException ioe) {
        }
    }
}

From source file:frameworks.Masken.java

public static void uncompressTarGZ(File tarFile, File dest) throws IOException {
    dest.mkdir();/*from ww w. j  av  a 2s .c o  m*/
    TarArchiveInputStream tarIn = null;

    tarIn = new TarArchiveInputStream(
            new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(tarFile))));

    TarArchiveEntry tarEntry = tarIn.getNextTarEntry();
    // tarIn is a TarArchiveInputStream
    while (tarEntry != null) {// create a file with the same name as the tarEntry
        File destPath = new File(dest, tarEntry.getName());
        System.out.println("working: " + destPath.getCanonicalPath());
        if (tarEntry.isDirectory()) {
            destPath.mkdirs();
        } else {
            if (!destPath.getParentFile().exists()) {
                destPath.getParentFile().mkdirs();
            }
            destPath.createNewFile();
            //byte [] btoRead = new byte[(int)tarEntry.getSize()];
            byte[] btoRead = new byte[1024];
            //FileInputStream fin 
            //  = new FileInputStream(destPath.getCanonicalPath());
            BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath));
            int len = 0;

            while ((len = tarIn.read(btoRead)) != -1) {
                bout.write(btoRead, 0, len);
            }

            bout.close();
            btoRead = null;

        }
        tarEntry = tarIn.getNextTarEntry();
    }
    tarIn.close();
}

From source file:edu.harvard.i2b2.eclipse.plugins.metadataLoader.util.FileUtil.java

public static void unZipAll(File source, File destination) throws IOException {
    System.out.println("Unzipping - " + source.getName());
    int BUFFER = 2048;

    ZipFile zip = new ZipFile(source);
    try {//from  w w  w  .jav  a2  s. c  o  m
        destination.getParentFile().mkdirs();
        Enumeration zipFileEntries = zip.entries();

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

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

            if (!entry.isDirectory()) {
                BufferedInputStream is = null;
                FileOutputStream fos = null;
                BufferedOutputStream dest = null;
                try {
                    is = new BufferedInputStream(zip.getInputStream(entry));
                    int currentByte;
                    // establish buffer for writing file
                    byte data[] = new byte[BUFFER];

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

                    // read and write until last byte is encountered
                    while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                        dest.write(data, 0, currentByte);
                    }
                } catch (Exception e) {
                    System.out.println("unable to extract entry:" + entry.getName());
                    throw e;
                } finally {
                    if (dest != null) {
                        dest.close();
                    }
                    if (fos != null) {
                        fos.close();
                    }
                    if (is != null) {
                        is.close();
                    }
                }
            } else {
                //Create directory
                destFile.mkdirs();
            }

            if (currentEntry.endsWith(".zip")) {
                // found a zip file, try to extract
                unZipAll(destFile, destinationParent);
                if (!destFile.delete()) {
                    System.out.println("Could not delete zip");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Failed to successfully unzip:" + source.getName());
    } finally {
        zip.close();
    }
    System.out.println("Done Unzipping:" + source.getName());
}

From source file:Files.java

/**
 * Copy a file./*  w  ww. j  a v  a2  s.  com*/
 *
 * @param source  Source file to copy.
 * @param target  Destination target file.
 * @param buff    The copy buffer.
 *
 * @throws IOException  Failed to copy file.
 */
public static void copy(final File source, final File target, final byte buff[]) throws IOException {
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(source));
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(target));

    int read;

    try {
        while ((read = in.read(buff)) != -1) {
            out.write(buff, 0, read);
        }
    } finally {
        Streams.flush(out);
        Streams.close(in);
        Streams.close(out);
    }
}

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

/**
 * Decompresses the specified archive.// w  w w. j a  va2  s .c o m
 * <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:Main.java

/**
 * Uncompresses zipped files//from   ww w . ja  v a  2  s.  c om
 * @param zippedFile The file to uncompress
 * @param destinationDir Where to put the files
 * @return  list of unzipped files
 * @throws java.io.IOException thrown if there is a problem finding or writing the files
 */
public static List<File> unzip(File zippedFile, File destinationDir) throws IOException {
    int buffer = 2048;

    List<File> unzippedFiles = new ArrayList<File>();

    BufferedOutputStream dest;
    BufferedInputStream is;
    ZipEntry entry;
    ZipFile zipfile = new ZipFile(zippedFile);
    Enumeration e = zipfile.entries();
    while (e.hasMoreElements()) {
        entry = (ZipEntry) e.nextElement();

        is = new BufferedInputStream(zipfile.getInputStream(entry));
        int count;
        byte data[] = new byte[buffer];

        File destFile;

        if (destinationDir != null) {
            destFile = new File(destinationDir, entry.getName());
        } else {
            destFile = new File(entry.getName());
        }

        FileOutputStream fos = new FileOutputStream(destFile);
        dest = new BufferedOutputStream(fos, buffer);
        try {
            while ((count = is.read(data, 0, buffer)) != -1) {
                dest.write(data, 0, count);
            }

            unzippedFiles.add(destFile);
        } finally {
            dest.flush();
            dest.close();
            is.close();
        }
    }

    return unzippedFiles;
}