Example usage for java.io BufferedOutputStream BufferedOutputStream

List of usage examples for java.io BufferedOutputStream BufferedOutputStream

Introduction

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

Prototype

public BufferedOutputStream(OutputStream out) 

Source Link

Document

Creates a new buffered output stream to write data to the specified underlying output stream.

Usage

From source file:com.jeson.xutils.http.callback.FileDownloadHandler.java

public File handleEntity(HttpEntity entity, RequestCallBackHandler callBackHandler, String target,
        boolean isResume, String responseFileName) throws IOException {
    if (entity == null || TextUtils.isEmpty(target)) {
        return null;
    }//from ww  w .j a  v a  2s .c om
    Log.e("target", "  target:" + target);
    File targetFile = new File(target);
    Log.e("target", "  targetFile:" + targetFile);
    if (!targetFile.exists()) {
        File dir = targetFile.getParentFile();
        if (dir.exists() || dir.mkdirs()) {
            targetFile.createNewFile();
        }
    }

    long current = 0;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        FileOutputStream fileOutputStream = null;
        if (isResume) {
            current = targetFile.length();
            fileOutputStream = new FileOutputStream(target, true);
        } else {
            fileOutputStream = new FileOutputStream(target);
        }
        long total = entity.getContentLength() + current;
        bis = new BufferedInputStream(entity.getContent());
        bos = new BufferedOutputStream(fileOutputStream);

        if (callBackHandler != null && !callBackHandler.updateProgress(total, current, true)) {
            return targetFile;
        }

        byte[] tmp = new byte[4096];
        int len;
        while ((len = bis.read(tmp)) != -1) {
            bos.write(tmp, 0, len);
            current += len;
            if (callBackHandler != null) {
                if (!callBackHandler.updateProgress(total, current, false)) {
                    return targetFile;
                }
            }
        }
        bos.flush();
        if (callBackHandler != null) {
            callBackHandler.updateProgress(total, current, true);
        }
    } finally {
        IOUtils.closeQuietly(bis);
        IOUtils.closeQuietly(bos);
    }

    if (targetFile.exists() && !TextUtils.isEmpty(responseFileName)) {
        File newFile = new File(targetFile.getParent(), responseFileName);
        while (newFile.exists()) {
            newFile = new File(targetFile.getParent(), System.currentTimeMillis() + responseFileName);
        }
        return targetFile.renameTo(newFile) ? newFile : targetFile;
    } else {
        return targetFile;
    }
}

From source file:net.sourceforge.floggy.maven.ZipUtils.java

/**
 * DOCUMENT ME!//ww  w.  ja v  a  2s  .c  om
*
* @param directories DOCUMENT ME!
* @param output DOCUMENT ME!
*
* @throws IOException DOCUMENT ME!
*/
public static void zip(File[] directories, File output) throws IOException {
    FileInputStream in = null;
    ZipOutputStream out = null;
    ZipEntry entry = null;

    Collection allFiles = new LinkedList();

    for (int i = 0; i < directories.length; i++) {
        allFiles.addAll(FileUtils.listFiles(directories[i], null, true));
    }

    out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(output)));

    for (Iterator iter = allFiles.iterator(); iter.hasNext();) {
        File temp = (File) iter.next();
        String name = getEntryName(directories, temp.getAbsolutePath());
        entry = new ZipEntry(name);
        out.putNextEntry(entry);

        if (!temp.isDirectory()) {
            in = new FileInputStream(temp);
            IOUtils.copy(in, out);
            in.close();
        }
    }

    out.close();
}

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  w  w w  . j  ava  2s .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.gsr.myschool.server.reporting.convocation.ConvocationController.java

@RequestMapping(value = "test", method = RequestMethod.GET, produces = "application/pdf")
@ResponseStatus(HttpStatus.OK)//  w w  w  .  j  ava2 s.c o  m
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:cn.isif.util_plus.http.callback.FileDownloadHandler.java

public File handleEntity(HttpEntity entity, RequestCallBackHandler callBackHandler, String target,
        boolean isResume, String responseFileName) throws IOException {
    if (entity == null || TextUtils.isEmpty(target)) {
        return null;
    }//from   w w w . j  a  v  a 2 s  .  co m

    File targetFile = new File(target);

    if (!targetFile.exists()) {
        File dir = targetFile.getParentFile();
        if (dir.exists() || dir.mkdirs()) {
            targetFile.createNewFile();
        }
    }

    long current = 0;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        FileOutputStream fileOutputStream = null;
        if (isResume) {
            current = targetFile.length();
            fileOutputStream = new FileOutputStream(target, true);
        } else {
            fileOutputStream = new FileOutputStream(target);
        }
        long total = entity.getContentLength() + current;
        bis = new BufferedInputStream(entity.getContent());
        bos = new BufferedOutputStream(fileOutputStream);

        if (callBackHandler != null && !callBackHandler.updateProgress(total, current, true)) {
            return targetFile;
        }

        byte[] tmp = new byte[4096];
        int len;
        while ((len = bis.read(tmp)) != -1) {
            bos.write(tmp, 0, len);
            current += len;
            if (callBackHandler != null) {
                if (!callBackHandler.updateProgress(total, current, false)) {
                    return targetFile;
                }
            }
        }
        bos.flush();
        if (callBackHandler != null) {
            callBackHandler.updateProgress(total, current, true);
        }
    } finally {
        IOUtils.closeQuietly(bis);
        IOUtils.closeQuietly(bos);
    }

    if (targetFile.exists() && !TextUtils.isEmpty(responseFileName)) {
        File newFile = new File(targetFile.getParent(), responseFileName);
        while (newFile.exists()) {
            newFile = new File(targetFile.getParent(), System.currentTimeMillis() + responseFileName);
        }
        return targetFile.renameTo(newFile) ? newFile : targetFile;
    } else {
        return targetFile;
    }
}

From source file:es.logongas.iothome.agent.storage.Storage.java

public void save(List<Measure> measures) {
    OutputStream outputStream = null;
    try {// w  ww .  j  a v  a 2 s  .  c om

        outputStream = new BufferedOutputStream(new FileOutputStream(fileName));
        objectMapper.writeValue(outputStream, measures);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException ex) {
            Logger.getLogger(Storage.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:com.milaboratory.core.io.CompressionType.java

private static OutputStream createOutputStream(CompressionType ct, OutputStream os, int buffer)
        throws IOException {
    switch (ct) {
    case None:/* w  w w  . ja v  a 2  s  . c  o m*/
        return os;
    case GZIP:
        return new GZIPOutputStream(os, buffer);
    case BZIP2:
        CompressorStreamFactory factory = new CompressorStreamFactory();
        try {
            return factory.createCompressorOutputStream(CompressorStreamFactory.BZIP2,
                    new BufferedOutputStream(os));
        } catch (CompressorException e) {
            throw new IOException(e);
        }
    }
    throw new NullPointerException();
}

From source file:com.l2jfree.network.legacy.NetworkThread.java

protected final void initConnection(Socket con) throws IOException {
    _connection = con;// w  w w .j  a v a2s.com
    _connectionIp = con.getInetAddress().getHostAddress();

    _in = new BufferedInputStream(con.getInputStream());
    _out = new BufferedOutputStream(con.getOutputStream());

    _blowfish = new NewCipher("_;v.]05-31!|+-%xT!^[$\00");
}

From source file:ezbake.deployer.impl.LocalFileArtifactWriter.java

@Override
public void writeArtifact(DeploymentMetadata metadata, DeploymentArtifact artifact) throws DeploymentException {
    File directory = new File(buildDirectoryPath(metadata));
    directory.mkdirs();/*from   www . j a v  a  2  s .  co m*/
    File artifactBinary = new File(buildFilePath(metadata));
    log.info("Writing artifact to {}", artifactBinary.getAbsolutePath());
    try {
        byte[] bytes = serializer.serialize(artifact);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(artifactBinary, false));
        bos.write(bytes);
        bos.close();
    } catch (TException ex) {
        log.error("Failed serialization", ex);
        throw new DeploymentException("Failed to serialize the artifact before writing. " + ex.getMessage());
    } catch (IOException ex) {
        log.error("IO Failure", ex);
        throw new DeploymentException("IO Failure writing artifact. " + ex.getMessage());
    }
}

From source file:org.openwms.common.comm.tcp.OSIPTelegramSerializer.java

/**
 * Writes the source object to an output stream using Java Serialization. The source object must implement {@link Serializable}.
 *///from  ww w .  j  av a2 s.c o m
@Override
public void serialize(Map<?, ?> map, OutputStream outputStream) throws IOException {
    BufferedOutputStream os = new BufferedOutputStream(outputStream);
    Map<String, String> headers = (Map<String, String>) map.get("headers");
    String header = String.valueOf(headers.get(CommHeader.SYNC_FIELD_NAME))
            + padLeft(
                    String.valueOf(CommConstants.TELEGRAM_LENGTH), CommHeader.LENGTH_MESSAGE_LENGTH_FIELD, "0")
            + String.valueOf(headers.get(CommHeader.SENDER_FIELD_NAME))
            + String.valueOf(headers.get(CommHeader.RECEIVER_FIELD_NAME)
                    + padLeft(String.valueOf(headers.get(CommHeader.SEQUENCE_FIELD_NAME)),
                            CommHeader.LENGTH_SEQUENCE_NO_FIELD, "0"));
    String s = header + ((Payload) map.get("payload")).asString();
    if (s.length() > CommConstants.TELEGRAM_LENGTH) {
        throw new MessageMismatchException("Defined telegram length exceeded, size is" + s.length());
    }
    os.write(padRight(s, CommConstants.TELEGRAM_LENGTH, CommConstants.TELEGRAM_FILLER_CHARACTER)
            .getBytes(Charset.defaultCharset()));
    os.write(CRLF);
    os.flush();
}