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.boxupp.utilities.PuppetUtilities.java

private void extrectFile(String saveFilePath, String moduleDirPath, String moduleName) {
    try {//from   w w  w  . ja  v a 2  s.c o  m
        File file = new File(saveFilePath);
        FileInputStream fin = new FileInputStream(file);
        BufferedInputStream in = new BufferedInputStream(fin);
        GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
        TarArchiveInputStream tarIn = new TarArchiveInputStream(gzIn);
        TarArchiveEntry entry = null;
        int length = 0;
        File unzipFile = null;
        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {
            if (entry.isDirectory()) {
                if (length == 0) {
                    File f = new File(moduleDirPath + entry.getName());
                    f.mkdirs();
                    unzipFile = f;
                    length++;
                } else {
                    File f = new File(moduleDirPath + entry.getName());
                    f.mkdirs();
                }
            } else {
                int count;
                byte data[] = new byte[4096];
                FileOutputStream fos;
                fos = new FileOutputStream(moduleDirPath + entry.getName());
                BufferedOutputStream dest = new BufferedOutputStream(fos, 4096);
                while ((count = tarIn.read(data, 0, 4096)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.close();
            }

        }
        File renamedFile = new File(moduleDirPath + "/" + moduleName);
        if (unzipFile.isDirectory()) {
            unzipFile.renameTo(renamedFile);
        }
        tarIn.close();

    } catch (IOException e) {
        logger.error("Error in unzip the module file :" + e.getMessage());
    }
}

From source file:DatabaseListener.java

/**
 * <p>Calculate and return an absolute pathname to the XML file to contain
 * our persistent storage information.</p>
 *
 * @return Absolute path to XML file.//from  ww  w . ja va 2  s .c  o m
 * @throws Exception if an input/output error occurs
 */
private String calculatePath() throws Exception {

    // Can we access the database via file I/O?
    String path = context.getRealPath(pathname);
    if (path != null) {
        return (path);
    }

    // Does a copy of this file already exist in our temporary directory
    File dir = (File) context.getAttribute("javax.servlet.context.tempdir");
    File file = new File(dir, "struts-example-database.xml");
    if (file.exists()) {
        return (file.getAbsolutePath());
    }

    // Copy the static resource to a temporary file and return its path
    InputStream is = context.getResourceAsStream(pathname);
    BufferedInputStream bis = new BufferedInputStream(is, 1024);
    FileOutputStream os = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(os, 1024);
    byte buffer[] = new byte[1024];
    while (true) {
        int n = bis.read(buffer);
        if (n <= 0) {
            break;
        }
        bos.write(buffer, 0, n);
    }
    bos.close();
    bis.close();
    return (file.getAbsolutePath());

}

From source file:edu.stanford.epadd.launcher.Main.java

public static void copy_stream_to_file(InputStream is, String filename) throws IOException {
    int bufsize = 64 * 1024;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {/*from  w w w  .j av a  2s.  c  o m*/
        File f = new File(filename);
        if (f.exists()) {
            // out.println ("File " + filename + " exists");
            boolean b = f.delete(); // best effort to delete file if it exists. this is because windows often complains about perms 
            if (!b)
                out.println("Warning: failed to delete " + filename);
        }
        bis = new BufferedInputStream(is, bufsize);
        bos = new BufferedOutputStream(new FileOutputStream(filename), bufsize);
        byte buf[] = new byte[bufsize];
        while (true) {
            int n = bis.read(buf);
            if (n <= 0)
                break;
            bos.write(buf, 0, n);
        }
    } catch (IOException ioe) {
        out.println("ERROR trying to copy data to file: " + filename + ", forging ahead nevertheless");
    } finally {
        if (bis != null)
            bis.close();
        if (bos != null)
            bos.close();
    }
}

From source file:jhc.redsniff.webdriver.download.FileDownloader.java

private void doDownloadUrlToFile(URL downloadURL, File downloadFile) throws Exception {
    HttpClient client = createHttpClient(downloadURL);
    HttpMethod getRequest = new GetMethod(downloadURL.toString());
    try {//from  w w  w  . ja  v a 2s.c  o  m
        int status = -1;
        for (int attempts = 0; attempts < MAX_ATTEMPTS && status != HTTP_SUCCESS_CODE; attempts++)
            status = client.executeMethod(getRequest);
        if (status != HTTP_SUCCESS_CODE)
            throw new Exception("Got " + status + " status trying to download file " + downloadURL.toString()
                    + " to " + downloadFile.toString());
        BufferedInputStream in = new BufferedInputStream(getRequest.getResponseBodyAsStream());
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(downloadFile));
        int offset = 0;
        int len = 4096;
        int bytes = 0;
        byte[] block = new byte[len];
        while ((bytes = in.read(block, offset, len)) > -1) {
            out.write(block, 0, bytes);
        }
        out.close();
        in.close();
    } catch (Exception e) {
        throw e;
    } finally {
        getRequest.releaseConnection();
    }
}

From source file:com.amaze.filemanager.filesystem.compressed.extractcontents.helpers.TarExtractor.java

private void extractEntry(@NonNull final Context context, TarArchiveInputStream inputStream,
        TarArchiveEntry entry, String outputDir) throws IOException {
    File outputFile = new File(outputDir, fixEntryName(entry.getName()));

    if (!outputFile.getCanonicalPath().startsWith(outputDir)) {
        throw new IOException("Incorrect TarArchiveEntry path!");
    }/*  ww  w.j  a  v a 2  s  .  c  o m*/

    if (entry.isDirectory()) {
        FileUtil.mkdir(outputFile, context);
        return;
    }

    if (!outputFile.getParentFile().exists()) {
        FileUtil.mkdir(outputFile.getParentFile(), context);
    }

    BufferedOutputStream outputStream = new BufferedOutputStream(FileUtil.getOutputStream(outputFile, context));
    try {
        int len;
        byte buf[] = new byte[GenericCopyUtil.DEFAULT_BUFFER_SIZE];
        while ((len = inputStream.read(buf)) != -1) {
            if (!listener.isCancelled()) {
                outputStream.write(buf, 0, len);
                ServiceWatcherUtil.position += len;
            } else
                break;
        }
    } finally {
        outputStream.close();
    }
}

From source file:com.amaze.filemanager.filesystem.compressed.extractcontents.helpers.GzipExtractor.java

private void extractEntry(@NonNull final Context context, TarArchiveInputStream inputStream,
        TarArchiveEntry entry, String outputDir) throws IOException {

    File outputFile = new File(outputDir, fixEntryName(entry.getName()));
    if (!outputFile.getCanonicalPath().startsWith(outputDir)) {
        throw new IOException("Incorrect ZipEntry path!");
    }/*w  w w  .jav a  2  s .c  om*/

    if (entry.isDirectory()) {
        FileUtil.mkdir(outputFile, context);
        return;
    }

    if (!outputFile.getParentFile().exists()) {
        FileUtil.mkdir(outputFile.getParentFile(), context);
    }

    BufferedOutputStream outputStream = new BufferedOutputStream(FileUtil.getOutputStream(outputFile, context));
    try {
        int len;
        byte buf[] = new byte[GenericCopyUtil.DEFAULT_BUFFER_SIZE];
        while ((len = inputStream.read(buf)) != -1) {
            if (!listener.isCancelled()) {
                outputStream.write(buf, 0, len);
                ServiceWatcherUtil.position += len;
            } else
                break;
        }
    } finally {
        outputStream.close();
    }
}

From source file:com.cloudseal.spring.client.namespace.CloudSealLogoutImageFilter.java

public void writeContent(HttpServletResponse response, String contentType, InputStream content)
        throws IOException {
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setContentType(contentType);

    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {/* w ww  .ja v  a 2 s .  c  o m*/
        input = new BufferedInputStream(content, DEFAULT_BUFFER_SIZE);
        output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length = 0;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
    } finally {
        output.close();
        input.close();
    }
}

From source file:com.gsr.myschool.server.reporting.bilan.BilanController.java

@RequestMapping(method = RequestMethod.GET, produces = "application/pdf")
@ResponseStatus(HttpStatus.OK)//from  w w w .  j a va2 s. c  om
public void generateBilan(@RequestParam(defaultValue = "") String status, @RequestParam String type,
        @RequestParam(required = false) String annee, @RequestParam(required = false) Boolean historic,
        HttpServletResponse response) {
    ReportDTO dto = null;
    Integer bilanType;
    DossierStatus dossierStatus = null;
    ValueList anneeScolaire;
    try {
        bilanType = Integer.parseInt(type);
        if (!Strings.isNullOrEmpty(status)) {
            dossierStatus = DossierStatus.valueOf(status);
        }
        anneeScolaire = valueListRepos.findByValueAndValueTypeCode(annee, ValueTypeCode.SCHOOL_YEAR);
        if (anneeScolaire == null) {
            anneeScolaire = getCurrentScholarYear();
        }
    } catch (Exception e) {
        return;
    }
    if (historic) {
        if (BilanType.CYCLE.ordinal() == bilanType) {
            dto = getReportCycleHistoric(status, dossierStatus, anneeScolaire);
        } else if (BilanType.NIVEAU_ETUDE.ordinal() == bilanType) {
            dto = getReportNiveauEtudeHistoric(status, dossierStatus, anneeScolaire);
        }
    } else {
        if (BilanType.CYCLE.ordinal() == bilanType) {
            dto = getReportCycle(status, dossierStatus, anneeScolaire);
        } else if (BilanType.NIVEAU_ETUDE.ordinal() == bilanType) {
            dto = getReportNiveauEtude(status, dossierStatus, anneeScolaire);
        }
    }

    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) {
        e.printStackTrace();
    }
}

From source file:ebay.dts.client.FileTransferActions.java

public void downloadFile2(String fileName, String jobId, String fileReferenceId) throws EbayConnectorException {

    String callName = "downloadFile";

    try {//from  ww w.j  av a  2  s . c o m

        FileTransferServicePort port = call.setFTSMessageContext(callName);
        com.ebay.marketplace.services.DownloadFileRequest request = new com.ebay.marketplace.services.DownloadFileRequest();
        request.setFileReferenceId(fileReferenceId);
        request.setTaskReferenceId(jobId);
        DownloadFileResponse response = port.downloadFile(request);
        if (response.getAck().equals(AckValue.SUCCESS)) {
            logger.debug(AckValue.SUCCESS.toString());
        } else {
            logger.error(response.getErrorMessage().getError().get(0).getMessage());
            throw new EbayConnectorException(response.getErrorMessage().getError().get(0).getMessage());
        }

        FileAttachment attachment = response.getFileAttachment();
        DataHandler dh = attachment.getData();

        try {
            InputStream in = dh.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(new GZIPInputStream(in));
            FileOutputStream fo = new FileOutputStream(new File(fileName)); // "C:/myDownLoadFile.gz"
            BufferedOutputStream bos = new BufferedOutputStream(fo);
            int bytes_read = 0;
            byte[] dataBuf = new byte[4096];
            while ((bytes_read = bis.read(dataBuf)) != -1) {
                bos.write(dataBuf, 0, bytes_read);
            }
            bis.close();
            bos.flush();
            bos.close();
            logger.info("File attachment has been saved successfully to " + fileName);

        } catch (IOException e) {
            logger.error("Exception caught while trying to save the attachement");
            throw new EbayConnectorException("Exception caught while trying to save the attachement", e);
        }

    } catch (Exception e) {
        throw new EbayConnectorException("Exception caught while trying to save the attachement", e);
    }

}

From source file:com.mesosphere.dcos.cassandra.executor.compress.SnappyCompressionDriver.java

@Override
public void decompress(InputStream source, OutputStream destination) throws IOException {
    SnappyInputStream compressedInputStream = null;
    BufferedOutputStream output = null;
    try {/* ww  w .j  a va 2 s  . co m*/
        compressedInputStream = new SnappyInputStream(new BufferedInputStream(source));
        output = new BufferedOutputStream(destination, DEFAULT_BUFFER_SIZE);

        int bytesRead;
        byte[] data = new byte[DEFAULT_BUFFER_SIZE];
        while ((bytesRead = compressedInputStream.read(data, 0, DEFAULT_BUFFER_SIZE)) != -1) {
            output.write(data, 0, bytesRead);
        }
    } finally {
        IOUtils.closeQuietly(compressedInputStream);
        IOUtils.closeQuietly(output);
    }
}