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.googlecode.jsfFlex.shared.tasks.sdk.UnzipTask.java

protected void performTask() {

    BufferedOutputStream bufferOutputStream = null;
    ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(_file));
    ZipEntry entry;/*  ww w  . ja v  a 2s .c om*/

    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.amytech.android.library.views.imagechooser.threads.MediaProcessorThread.java

protected void processPicasaMedia(String path, String extension) throws Exception {
    if (BuildConfig.DEBUG) {
        Log.i(TAG, "Picasa Started");
    }//from  ww w. ja  v  a  2  s. c  o m
    try {
        InputStream inputStream = context.getContentResolver().openInputStream(Uri.parse(path));

        filePath = FileUtils.getDirectory(foldername) + File.separator
                + Calendar.getInstance().getTimeInMillis() + extension;

        BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(filePath));
        byte[] buf = new byte[2048];
        int len;
        while ((len = inputStream.read(buf)) > 0) {
            outStream.write(buf, 0, len);
        }
        inputStream.close();
        outStream.close();
        process();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    if (BuildConfig.DEBUG) {
        Log.i(TAG, "Picasa Done");
    }
}

From source file:com.bmc.gibraltar.automation.dataprovider.RestDataProvider.java

/**
 * Download file with the {@param attachmentName} name that was uploaded for the task
 *
 * @param taskGuid       task GUID//from ww  w  . j  a v a 2s  . co m
 * @param attachmentName name of the file that was attached to the task
 * @return downloaded file
 */
@Step
public File getTaskAttachment(String taskGuid, String attachmentName) {
    LOG.info("Downloading an attachment with the name: " + attachmentName + " of the task with GUID: "
            + taskGuid);
    File downloadedFile = null;
    try {
        InputStream is = recordApi
                .getRecordInstanceContent(RestApiData.TASK_RECORD_DEFINITION, taskGuid, attachmentName)
                .extract().asInputStream();
        downloadedFile = new File(System.getProperty("java.io.tmpdir"), attachmentName);
        BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(downloadedFile));
        byte[] b = new byte[1024 * 1024];
        int read;
        while ((read = is.read(b)) > -1) {
            bout.write(b, 0, read);
        }
        bout.flush();
        bout.close();
        is.close();
    } catch (IOException e) {
        LOG.error("Cannot download a file " + attachmentName + " from server: " + e);
        e.printStackTrace();
    }
    return downloadedFile;
}

From source file:edu.dfci.cccb.mev.dataset.domain.gzip.GzipTsvInput.java

@Override
public InputStream input() throws IOException {
    if (log.isDebugEnabled())
        log.debug(url);//w  w w  .j  a v a2 s. co  m

    GZIPInputStream zis = null;
    BufferedOutputStream dest = null;
    BufferedInputStream bis = null;
    File unzipped = new TemporaryFile();
    try {
        URLConnection urlc = url.openConnection();
        zis = new GZIPInputStream(urlc.getInputStream());

        int count;
        byte data[] = new byte[BUFFER];
        // write the files to the disk

        FileOutputStream fos = new FileOutputStream(unzipped);
        if (log.isDebugEnabled())
            log.debug("Unzipping SOFT file to " + unzipped.getAbsolutePath());

        dest = new BufferedOutputStream(fos, BUFFER);
        while ((count = zis.read(data, 0, BUFFER)) != -1) {
            dest.write(data, 0, count);
        }
        dest.flush();
        dest.close();
        return new FileInputStream(unzipped);

    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException ioe) {
            }
        }
        if (dest != null) {
            try {
                dest.close();
            } catch (IOException ioe) {
            }
        }
        if (zis != null) {
            try {
                zis.close();
            } catch (IOException ioe) {
            }
        }
    }

}

From source file:gov.usgs.anss.query.MultiplexedMSOutputer.java

/**
 * This does the hard work of sorting - called as a shutdown hook.
 * TODO: consider recursion./*from  ww  w . j ava2 s  .  c o m*/
 * @param outputName name for the output file.
 * @param files list of MiniSEED files to multiplex.
 * @param cleanup flag indicating whether to cleanup after ourselves or not.
 * @throws IOException
 */
public static void multiplexFiles(String outputName, List<File> files, boolean cleanup, boolean allowEmpty)
        throws IOException {
    ArrayList<File> cleanupFiles = new ArrayList<File>(files);
    ArrayList<File> moreFiles = new ArrayList<File>();

    File outputFile = new File(outputName);
    File tempOutputFile = new File(outputName + ".tmp");

    do {
        // This checks if we're in a subsequent (i.e. not the first) iteration and if there are any more files to process...?
        if (!moreFiles.isEmpty()) {
            logger.info("more files left to multiplex...");
            FileUtils.deleteQuietly(tempOutputFile);
            FileUtils.moveFile(outputFile, tempOutputFile);

            cleanupFiles.add(tempOutputFile);
            moreFiles.add(tempOutputFile);
            files = moreFiles;
            moreFiles = new ArrayList<File>();
        }

        logger.log(Level.FINE, "Multiplexing blocks from {0} temp files to {1}",
                new Object[] { files.size(), outputName });
        BufferedOutputStream out = new BufferedOutputStream(FileUtils.openOutputStream(outputFile));

        // The hard part, sorting the temp files...
        TreeMap<MiniSeed, FileInputStream> blks = new TreeMap<MiniSeed, FileInputStream>(
                new MiniSeedTimeOnlyComparator());
        // Prime the TreeMap
        logger.log(Level.FINEST, "Priming the TreeMap with files: {0}", files);
        for (File file : files) {
            logger.log(Level.INFO, "Reading first block from {0}", file.toString());
            try {
                FileInputStream fs = FileUtils.openInputStream(file);
                MiniSeed ms = getNextValidMiniSeed(fs, allowEmpty);
                if (ms != null) {
                    blks.put(ms, fs);
                } else {
                    logger.log(Level.WARNING, "Failed to read valid MiniSEED block from {0}", file.toString());
                }
            } catch (IOException ex) {
                // Catch "Too many open files" i.e. hitting ulimit, throw anything else.
                if (ex.getMessage().contains("Too many open files")) {
                    logger.log(Level.INFO, "Too many open files - {0} deferred.", file.toString());
                    moreFiles.add(file);
                } else
                    throw ex;
            }
        }

        while (!blks.isEmpty()) {
            MiniSeed next = blks.firstKey();
            out.write(next.getBuf(), 0, next.getBlockSize());

            FileInputStream fs = blks.remove(next);
            next = getNextValidMiniSeed(fs, allowEmpty);
            if (next != null) {
                blks.put(next, fs);
            } else {
                fs.close();
            }
        }

        out.close();
    } while (!moreFiles.isEmpty());

    if (cleanup) {
        logger.log(Level.INFO, "Cleaning up...");
        for (File file : cleanupFiles) {
            FileUtils.deleteQuietly(file);
        }
    }
}

From source file:com.amytech.android.library.views.imagechooser.threads.MediaProcessorThread.java

protected void processGooglePhotosMedia(String path, String extension) throws Exception {
    if (BuildConfig.DEBUG) {
        Log.i(TAG, "Google photos Started");
        Log.i(TAG, "URI: " + path);
        Log.i(TAG, "Extension: " + extension);
    }//from  www.j a  v  a  2s  .co m
    String retrievedExtension = checkExtension(Uri.parse(path));
    if (retrievedExtension != null && !TextUtils.isEmpty(retrievedExtension)) {
        extension = "." + retrievedExtension;
    }
    try {

        filePath = FileUtils.getDirectory(foldername) + File.separator
                + Calendar.getInstance().getTimeInMillis() + extension;

        ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver()
                .openFileDescriptor(Uri.parse(path), "r");

        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();

        InputStream inputStream = new FileInputStream(fileDescriptor);

        BufferedInputStream reader = new BufferedInputStream(inputStream);

        BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(filePath));
        byte[] buf = new byte[2048];
        int len;
        while ((len = reader.read(buf)) > 0) {
            outStream.write(buf, 0, len);
        }
        outStream.flush();
        outStream.close();
        inputStream.close();
        process();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    if (BuildConfig.DEBUG) {
        Log.i(TAG, "Picasa Done");
    }
}

From source file:com.w4t.engine.requests.UploadRequestFileItem.java

/**
 * <p>a convenience method to write an uploaded item to disk. The client code 
 * is not concerned with whether or not the item is stored in memory, or on 
 * disk in a temporary location. They just want to write the uploaded item to
 * a file.</p>//www . ja v  a  2 s . c  om
 * 
 * <p>This implementation first attempts to rename the uploaded item to the
 * specified destination file, if the item was originally written to disk.
 * Otherwise, the data will be copied to the specified file.</p>
 * 
 * <p>This method is only guaranteed to work <em>once</em>, the first time it
 * is invoked for a particular item. This is because, in the event that the
 * method renames a temporary file, that file will no longer be available to
 * copy or rename again at a later time.</p>
 * 
 * @param file The <code>File</code> into which the uploaded item should be
 *          stored.
 * @exception Exception if an error occurs.
 */
public void write(final File file) throws IOException {
    if (isInMemory()) {
        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(file);
            fout.write(get());
        } finally {
            if (fout != null) {
                fout.close();
            }
        }
    } else {
        File outputFile = getStoreLocation();
        if (outputFile != null) {
            /*
             * The uploaded file is being stored on disk in a temporary location so
             * move it to the desired file.
             */
            if (!outputFile.renameTo(file)) {
                BufferedInputStream in = null;
                BufferedOutputStream out = null;
                try {
                    in = new BufferedInputStream(new FileInputStream(outputFile));
                    out = new BufferedOutputStream(new FileOutputStream(file));
                    byte[] bytes = new byte[2048];
                    int s = 0;
                    while ((s = in.read(bytes)) != -1) {
                        out.write(bytes, 0, s);
                    }
                } finally {
                    try {
                        if (in != null) {
                            in.close();
                        }
                    } catch (IOException e) {
                        // ignore
                    }
                    try {
                        if (out != null) {
                            out.close();
                        }
                    } catch (IOException e) {
                        // ignore
                    }
                }
            }
        } else {
            /*
             * For whatever reason we cannot write the file to disk.
             */
            throw new IOException("Cannot write uploaded file to disk!");
        }
    }
}

From source file:com.rokolabs.app.common.image.ImageFetcher.java

/**
 * Download a bitmap from a URL and write the content to an output stream.
 * //from w w w  .j a v a 2  s.  c  o m
 * @param urlString
 *            The URL to fetch
 * @return true if successful, false otherwise
 */
public boolean downloadUrlToStream(String urlString, OutputStream outputStream) {
    BufferedOutputStream out = null;
    BufferedInputStream in = null;

    try {
        HttpResponse response = mClient.syncGetRaw(urlString, null);
        in = new BufferedInputStream(response.getEntity().getContent(), IO_BUFFER_SIZE);
        out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE);

        byte[] buffer = new byte[IO_BUFFER_SIZE];
        int len = 0;
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        return true;
    } catch (final IOException e) {
        Log.e(TAG, "Error in downloadBitmap - " + urlString, e);
    } finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (final IOException e) {
        }
    }
    return false;
}

From source file:com.sqli.liferay.imex.util.xml.ZipUtils.java

public void _unzipArchive(File archive, File outputDir) throws IOException {
    BufferedOutputStream dest = null;
    FileInputStream fis = new FileInputStream(archive);
    CheckedInputStream checksum = new CheckedInputStream(fis, new Adler32());
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(checksum));
    ZipEntry entry;/*from   ww  w  .  j a v  a2 s  .co  m*/
    while ((entry = zis.getNextEntry()) != null) {
        log.debug("Extracting: " + entry);
        int count;
        byte data[] = new byte[BUFFER];
        // write the files to the disk
        FileOutputStream fos = new FileOutputStream(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();
    log.debug("Checksum:" + checksum.getChecksum().getValue());

}

From source file:org.apache.ofbiz.base.util.UtilHttp.java

/**
 * Stream binary content from InputStream to OutputStream
 * This method does not close the streams passed
 *
 * @param out OutputStream content should go to
 * @param in InputStream of the actual content
 * @param length Size (in bytes) of the content
 * @throws IOException//from   w  w  w . j a v  a 2  s . c om
 */
public static void streamContent(OutputStream out, InputStream in, int length) throws IOException {
    int bufferSize = 512; // same as the default buffer size; change as needed

    // make sure we have something to write to
    if (out == null) {
        throw new IOException("Attempt to write to null output stream");
    }

    // make sure we have something to read from
    if (in == null) {
        throw new IOException("Attempt to read from null input stream");
    }

    // make sure we have some content
    if (length == 0) {
        throw new IOException("Attempt to write 0 bytes of content to output stream");
    }

    // initialize the buffered streams
    BufferedOutputStream bos = new BufferedOutputStream(out, bufferSize);
    BufferedInputStream bis = new BufferedInputStream(in, bufferSize);

    byte[] buffer = new byte[length];
    int read = 0;
    try {
        while ((read = bis.read(buffer, 0, buffer.length)) != -1) {
            bos.write(buffer, 0, read);
        }
    } catch (IOException e) {
        Debug.logError(e, "Problem reading/writing buffers", module);
        bis.close();
        bos.close();
        throw e;
    } finally {
        if (bis != null) {
            bis.close();
        }
        if (bos != null) {
            bos.flush();
            bos.close();
        }
    }
}