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:net.sf.sahi.util.Utils.java

public static byte[] getBytes(final InputStream in, final int contentLength) throws IOException {
    BufferedInputStream bin = new BufferedInputStream(in, BUFFER_SIZE);

    if (contentLength != -1) {
        int totalBytesRead = 0;
        byte[] buffer = new byte[contentLength];
        while (totalBytesRead < contentLength) {
            int bytesRead = -1;
            try {
                bytesRead = bin.read(buffer, totalBytesRead, contentLength - totalBytesRead);
            } catch (EOFException e) {
            }//w w  w .  j  av  a  2 s .  co m
            if (bytesRead == -1) {
                break;
            }
            totalBytesRead += bytesRead;
        }
        return buffer;
    } else {
        ByteArrayOutputStream byteArOut = new ByteArrayOutputStream();
        BufferedOutputStream bout = new BufferedOutputStream(byteArOut);
        try {
            int totalBytesRead = 0;
            byte[] buffer = new byte[BUFFER_SIZE];

            while (true) {
                int bytesRead = -1;
                try {
                    bytesRead = bin.read(buffer);
                } catch (EOFException e) {
                }
                if (bytesRead == -1) {
                    break;
                }
                bout.write(buffer, 0, bytesRead);
                totalBytesRead += bytesRead;
            }
        } catch (SocketTimeoutException ste) {
            ste.printStackTrace();
        }
        bout.flush();
        bout.close();
        return byteArOut.toByteArray();
    }
}

From source file:net.dfs.remote.filestorage.impl.StorageManagerImpl.java

/**
 * fileStorage will be responsible in storing the File object in the local
 * storage device. A notification indicating the name of the File object and the 
 * remote machine's address will be sent to the {@link FileLocationTracker}. 
 * <p>/*from   www .  j av  a 2  s.c  o  m*/
 * An OutPutStream of the FileObject will be saved in the local storage device.
 * IOException will be thrown on a failure. It returns no value.
 * 
 * @param storeFile an object of the type {@link FileStorageModel}
 */
public void fileStorage(FileStorageModel storeFile) {

    try {

        String savePath = path + storeFile.fileName;

        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(savePath));
        outputStream.write(storeFile.bytes, 0, storeFile.bytesRead);
        outputStream.flush();
        outputStream.close();

        log.debug("File " + storeFile.fileName + " saved to the disk");

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.edgenius.core.util.ZipFileUtil.java

public static void expandZipToFolder(InputStream is, String destFolder) throws ZipFileUtilException {
    // got our directory, so write out the input file and expand the zip file
    // this is really a hack - write it out temporarily then read it back in again! urg!!!!
    ZipInputStream zis = new ZipInputStream(is);
    int count;//  ww w.  j  a  v  a  2  s.  c o m
    byte data[] = new byte[BUFFER_SIZE];
    ZipEntry entry = null;
    BufferedOutputStream dest = null;
    String entryName = null;

    try {

        // work through each file, creating a node for each file
        while ((entry = zis.getNextEntry()) != null) {
            entryName = entry.getName();
            if (!entry.isDirectory()) {

                String destName = destFolder + File.separator + entryName;
                //It must sort out the directory information to current OS. 
                //e.g, if zip file is zipped under windows, but unzip in linux.  
                destName = FileUtil.makeCanonicalPath(destName);

                prepareDirectory(destName);

                FileOutputStream fos = new FileOutputStream(destName);
                dest = new BufferedOutputStream(fos, BUFFER_SIZE);
                while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                IOUtils.closeQuietly(dest);
                dest = null;
            } else {
                String destName = destFolder + File.separator + entryName;
                destName = FileUtil.makeCanonicalPath(destName);
                new File(destName).mkdirs();
            }

        }

    } catch (IOException ioe) {

        log.error("Exception occured processing entries in zip file. Entry was " + entryName, ioe);
        throw new ZipFileUtilException(
                "Exception occured processing entries in zip file. Entry was " + entryName, ioe);

    } finally {
        IOUtils.closeQuietly(dest);
        IOUtils.closeQuietly(zis);
    }
}

From source file:com.piaoyou.util.FileUtil.java

public static void copyFile(InputStream inputStream1, OutputStream outputStream1) throws IOException {

    BufferedInputStream inputStream = null;
    BufferedOutputStream outputStream = null;
    byte[] block = new byte[1024];
    try {//  w  ww .j  a v  a  2s .  com
        inputStream = new BufferedInputStream(inputStream1);
        outputStream = new BufferedOutputStream(outputStream1);
        while (true) {
            int readLength = inputStream.read(block);
            if (readLength == -1)
                break;// end of file
            outputStream.write(block, 0, readLength);
        }
    } catch (Exception ee) {
        ee.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ex) {
                log.error("Cannot close stream", ex);
            }
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException ex) {
                log.error("Cannot close stream", ex);
            }
        }
    }
}

From source file:c3.ops.priam.compress.SnappyCompression.java

private void decompress(InputStream input, OutputStream output) throws IOException {
    SnappyInputStream is = new SnappyInputStream(new BufferedInputStream(input));
    byte data[] = new byte[BUFFER];
    BufferedOutputStream dest1 = new BufferedOutputStream(output, BUFFER);
    try {//from   w w  w .  j av  a 2  s  . co m
        int c;
        while ((c = is.read(data, 0, BUFFER)) != -1) {
            dest1.write(data, 0, c);
        }
    } finally {
        IOUtils.closeQuietly(dest1);
        IOUtils.closeQuietly(is);
    }
}

From source file:com.aurel.track.admin.customize.category.report.ReportBL.java

/**
 * Save the new template at given location(repository, project)
 * @param repository/* www  .  j ava  2 s.  c om*/
 * @param personID
 * @param project
 * @param templateName
 * @param uploadZip
 * @return an error meassage if exist
 */
public static void saveTemplate(Integer id, ZipInputStream zis) throws IOException {
    // specify buffer size for extraction
    final int BUFFER = 2048;
    // Open Zip file for reading
    File unzipDestinationDirectory = getDirTemplate(id);
    BufferedOutputStream dest = null;
    ZipEntry entry;
    while ((entry = zis.getNextEntry()) != null) {
        File destFile = new File(unzipDestinationDirectory, entry.getName());
        if (destFile.exists()) {
            destFile.delete();
        }
        // grab file's parent directory structure
        File destinationParent = destFile.getParentFile();
        // create the parent directory structure if needed
        destinationParent.mkdirs();
        int count;
        byte data[] = new byte[BUFFER];
        // write the files to the disk
        FileOutputStream fos = new FileOutputStream(destFile);
        dest = new BufferedOutputStream(fos, BUFFER);
        while ((count = zis.read(data, 0, BUFFER)) != -1) {
            dest.write(data, 0, count);
        }
        dest.flush();
        dest.close();
    }
    zis.close();
}

From source file:com.gsr.myschool.server.reporting.convocation.ConvocationController.java

@RequestMapping(method = RequestMethod.GET, produces = "application/pdf")
@ResponseStatus(HttpStatus.OK)/*from   w  w w  .j a  v a2s  . c  om*/
public void generateConvocation(@RequestParam String number, HttpServletResponse response) {
    ReportDTO dto = convocationService.generateConvocation(number);
    try {
        response.addHeader("Content-Disposition", "attachment; filename=" + dto.getFileName());

        BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        byte[] result = reportService.generatePdf(dto);

        outputStream.write(result, 0, result.length);
        outputStream.flush();
        outputStream.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.gsr.myschool.server.reporting.convocation.ConvocationController.java

@RequestMapping(value = "test", method = RequestMethod.GET, produces = "application/pdf")
@ResponseStatus(HttpStatus.OK)/*from   www . j a va  2 s . com*/
public void generateReportTest(@RequestParam String niveauId, @RequestParam String sessionId,
        HttpServletResponse response) {
    ReportDTO dto = convocationService.generateConvocationTest(Long.valueOf(niveauId), Long.valueOf(sessionId));
    try {
        response.addHeader("Content-Disposition", "attachment; filename=convocation.pdf");

        BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        byte[] result = reportService.generatePdf(dto);

        outputStream.write(result, 0, result.length);
        outputStream.flush();
        outputStream.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

public static void unzip(File zipFile) {
    FileInputStream fileInputStream = null;
    ZipInputStream zipInputStream = null;
    FileOutputStream fileoutputstream = null;
    BufferedOutputStream bufferedoutputstream = null;
    try {// ww  w .  ja v a2  s  .  co m
        fileInputStream = new FileInputStream(zipFile);
        zipInputStream = new ZipInputStream(fileInputStream);
        java.util.zip.ZipEntry zipEntry;
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            byte abyte0[] = new byte[BUFFER];
            fileoutputstream = new FileOutputStream(zipEntry.getName());
            bufferedoutputstream = new BufferedOutputStream(fileoutputstream, BUFFER);
            int i;
            while ((i = zipInputStream.read(abyte0, 0, BUFFER)) != -1) {
                bufferedoutputstream.write(abyte0, 0, i);
            }
            bufferedoutputstream.flush();
            IOUtils.closeStream(fileoutputstream);
            IOUtils.closeStream(bufferedoutputstream);
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(fileInputStream);
        IOUtils.closeStream(zipInputStream);
        IOUtils.closeStream(fileoutputstream);
        IOUtils.closeStream(bufferedoutputstream);
    }
}

From source file:com.aurel.track.util.PluginUtils.java

/**
 * Unzip this file into the given directory. If the zipFile is called "zipFile.zip",
 * the files will be placed into "targetDir/zipFile".
 * @param zipFile//from w  ww.  ja v  a 2s  .co  m
 * @param targetDir
 */
public static void unzipFileIntoDirectory(File zipFile, File targetDir) {
    try {
        LOGGER.debug("Expanding Genji extension file " + zipFile.getName());
        int BUFFER = 2048;
        File file = zipFile;
        ZipFile zip = new ZipFile(file);
        String newPath = targetDir + File.separator
                + zipFile.getName().substring(0, zipFile.getName().length() - 4);
        new File(newPath).mkdir();
        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(newPath, 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 = new BufferedInputStream(zip.getInputStream(entry));
                int currentByte;
                // establish buffer for writing file
                byte data[] = new byte[BUFFER];
                // write the current file to disk
                LOGGER.debug("Unzipping " + destFile.getAbsolutePath());
                FileOutputStream fos = new FileOutputStream(destFile);
                BufferedOutputStream 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);
                }
                dest.flush();
                dest.close();
                is.close();
            }
        }
    } catch (Exception e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }
}