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:edu.jhu.hlt.concrete.serialization.TarCompactCommunicationSerializer.java

@Override
public void toTar(Collection<Communication> commColl, Path outPath) throws ConcreteException, IOException {
    try (OutputStream os = Files.newOutputStream(outPath);
            BufferedOutputStream bos = new BufferedOutputStream(os);
            TarArchiveOutputStream tos = new TarArchiveOutputStream(bos);) {
        for (Communication c : commColl) {
            TarArchiveEntry entry = new TarArchiveEntry(c.getId() + ".concrete");
            byte[] cbytes = this.toBytes(c);
            entry.setSize(cbytes.length);
            tos.putArchiveEntry(entry);//w w w.j a  v  a 2s. c o  m
            try (ByteArrayInputStream bis = new ByteArrayInputStream(cbytes)) {
                IOUtils.copy(bis, tos);
                tos.closeArchiveEntry();
            }
        }

    } catch (IOException e) {
        throw new ConcreteException(e);
    }
}

From source file:boosta.artem.services.FTPResultReader.java

public void readResult() {
    String server = "62.210.82.210";
    int port = 55021;
    String user = "misha_p";
    String pass = "GfhjkM1983";

    FTPClient ftpClient = new FTPClient();
    try {//from ww w  . ja  v  a  2  s.  co  m

        ftpClient.connect(server, port);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.ASCII_FILE_TYPE);

        // APPROACH #1: using retrieveFile(String, OutputStream)
        String remoteFile = Main.remote_out_path;
        System.out.println(remoteFile);
        //String remoteFile = "/results/ttgenerate.txt";
        String downlFile = Main.file_name;
        System.out.println(downlFile);
        File downloadFile = new File(downlFile);
        OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile));

        boolean success = ftpClient.retrieveFile(remoteFile, outputStream);

        outputStream.close();

        if (success) {
            System.out.println(" ?   FTP!!!");
        } else {
            System.out.println("  ?   TFP!!!");
        }

    } catch (IOException ex) {
        System.out.println("   ? FTP  !!!");
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            System.out.println(" ? ?? ? FTP!!!");
        }
    }
}

From source file:com.pdftron.pdf.utils.BasicHTTPDownloadTask.java

@Override
protected Boolean doInBackground(String... params) {
    URL url;/* w w w.  j  ava2s .  c  o  m*/
    OutputStream filestream = null;
    try {
        url = new URL(mURL);

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        filestream = new BufferedOutputStream(new FileOutputStream(mSaveFile));

        IOUtils.copy(urlConnection.getInputStream(), filestream);

        filestream.close();
    } catch (MalformedURLException e) {
        return false;
    } catch (IOException e) {
        try {
            if (filestream != null)
                filestream.close();
        } catch (IOException e2) {
        }
        return false;
    }
    return true;
}

From source file:net.sf.mcf2pdf.mcfelements.util.PdfUtil.java

/**
 * Converts an FO file to a PDF file using Apache FOP.
 *
 * @param fo the FO file//w w  w.  j  a va 2  s. co  m
 * @param pdf the target PDF file
 * @param dpi the DPI resolution to use for bitmaps in the PDF
 * @throws IOException In case of an I/O problem
 * @throws FOPException In case of a FOP problem
 * @throws TransformerException In case of XML transformer problem
 */
@SuppressWarnings("rawtypes")
public static void convertFO2PDF(InputStream fo, OutputStream pdf, int dpi)
        throws IOException, FOPException, TransformerException {

    FopFactory fopFactory = FopFactory.newInstance();

    FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
    // configure foUserAgent as desired
    foUserAgent.setTargetResolution(dpi);

    // Setup output stream. Note: Using BufferedOutputStream
    // for performance reasons (helpful with FileOutputStreams).
    OutputStream out = new BufferedOutputStream(pdf);

    // Construct fop with desired output format
    Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

    // Setup JAXP using identity transformer
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer(); // identity
                                                        // transformer

    // Setup input stream
    Source src = new StreamSource(fo);

    // Resulting SAX events (the generated FO) must be piped through to FOP
    Result res = new SAXResult(fop.getDefaultHandler());

    // Start XSLT transformation and FOP processing
    transformer.transform(src, res);

    // Result processing
    FormattingResults foResults = fop.getResults();
    java.util.List pageSequences = foResults.getPageSequences();
    for (java.util.Iterator it = pageSequences.iterator(); it.hasNext();) {
        PageSequenceResults pageSequenceResults = (PageSequenceResults) it.next();
        log.debug("PageSequence "
                + (String.valueOf(pageSequenceResults.getID()).length() > 0 ? pageSequenceResults.getID()
                        : "<no id>")
                + " generated " + pageSequenceResults.getPageCount() + " pages.");
    }
    log.info("Generated " + foResults.getPageCount() + " PDF pages in total.");
    out.flush();
}

From source file:com.iyonger.apm.web.util.FileDownloadUtils.java

/**
 * Download the given file to the given {@link HttpServletResponse}.
 *
 * @param response {@link HttpServletResponse}
 * @param file     file path/*from   ww  w . j av a 2 s.  c om*/
 * @return true if succeeded
 */
public static boolean downloadFile(HttpServletResponse response, File file) {
    if (file == null || !file.exists()) {
        return false;
    }
    boolean result = true;
    response.reset();
    response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
    response.setContentType("application/octet-stream");
    response.addHeader("Content-Length", "" + file.length());
    InputStream fis = null;
    byte[] buffer = new byte[FILE_DOWNLOAD_BUFFER_SIZE];
    OutputStream toClient = null;
    try {
        fis = new BufferedInputStream(new FileInputStream(file));
        toClient = new BufferedOutputStream(response.getOutputStream());
        int readLength;
        while (((readLength = fis.read(buffer)) != -1)) {
            toClient.write(buffer, 0, readLength);
        }
        toClient.flush();
    } catch (FileNotFoundException e) {
        LOGGER.error("file not found:" + file.getAbsolutePath(), e);
        result = false;
    } catch (IOException e) {
        LOGGER.error("read file error:" + file.getAbsolutePath(), e);
        result = false;
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(toClient);
    }
    return result;
}

From source file:com.eryansky.common.utils.io.IoUtils.java

public static void writeStringToFile(String content, String filePath) {
    BufferedOutputStream outputStream = null;
    try {// www. j a v a  2s .c  o  m
        outputStream = new BufferedOutputStream(new FileOutputStream(getFile(filePath)));
        outputStream.write(content.getBytes());
        outputStream.flush();
    } catch (Exception e) {
        //      throw new ServiceException("Couldn't write file " + filePath, e);
    } finally {
        IoUtils.closeSilently(outputStream);
    }
}

From source file:org.sonarqube.shell.services.ExportToFileService.java

public void export(Object result, File dest) {
    requireNonNull(result);/*from  w w  w. j a va2s  .  c  o m*/
    requireNonNull(dest);
    try (FileOutputStream fos = new FileOutputStream(dest); OutputStream out = new BufferedOutputStream(fos)) {
        context.getMarshaller().marshal(result, out);
    } catch (JAXBException e) {
        LOGGER.error("Failed to marshall the result.", e);
    } catch (IOException e) {
        LOGGER.error("Failed to save the file.", e);
    }
}

From source file:com.parse.ParseFileUtilsTest.java

@Test
public void testReadFileToString() throws Exception {
    File file = temporaryFolder.newFile("file.txt");
    BufferedOutputStream out = null;
    try {//from w  ww.ja v a2  s  . c  om
        out = new BufferedOutputStream(new FileOutputStream(file));
        out.write(TEST_STRING.getBytes("UTF-8"));
    } finally {
        ParseIOUtils.closeQuietly(out);
    }

    assertEquals(TEST_STRING, ParseFileUtils.readFileToString(file, "UTF-8"));
}

From source file:cn.mdict.utils.IOUtil.java

public static boolean streamDuplicate(InputStream is, OutputStream os, int bufferSize,
        StatusReport statusReport) {//from   ww w  . ja va 2  s .c o  m
    is = new BufferedInputStream(is);
    os = new BufferedOutputStream(os);
    byte[] buffer = new byte[bufferSize];
    int length;
    int count = 0;
    boolean result = false;
    try {
        while (((statusReport == null) || !statusReport.isCanceled()) && (length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
            count += length;
            if (statusReport != null)
                statusReport.onProgressUpdate(count);
        }
        os.flush();
        result = true;
        if (statusReport != null) {
            if (statusReport.isCanceled())
                statusReport.onInterrupted();
            else
                statusReport.onComplete();
        }
    } catch (Exception e) {
        if (statusReport != null)
            statusReport.onError(e);
        else
            e.printStackTrace();
    } finally {
        forceClose(is);
        forceClose(os);
    }
    return result;
}

From source file:outfox.dict.contest.util.FileUtils.java

/**
 * /* www.ja  v a 2s.c o  m*/
 * @param b
 * @param outputFile
 * @return
 */
public static File getFileFromBytes(byte[] b, String outputFile) {
    File file = null;
    BufferedOutputStream stream = null;
    try {

        file = new File(outputFile);
        FileOutputStream fstream = new FileOutputStream(file);
        stream = new BufferedOutputStream(fstream);
        stream.write(b);
    } catch (Exception e) {
        LOG.error("FileUtils.getFileFromBytes in catch error...", e);
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                LOG.error("FileUtils.getFileFromBytes in finally error...", e);
            }
        }
    }
    return file;
}