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.att.voice.TTS.java

public void say(String text, String file) {

    text = text.replace("\"", "");

    try {/*from  w  ww.  jav  a  2  s .co m*/

        HttpPost httpPost = new HttpPost("https://api.att.com/speech/v3/textToSpeech");
        httpPost.setHeader("Authorization", "Bearer " + mAuthToken);
        httpPost.setHeader("Accept", "audio/x-wav");
        httpPost.setHeader("Content-Type", "text/plain");
        httpPost.setHeader("Tempo", "-16");
        HttpEntity entity = new StringEntity(text, "UTF-8");

        httpPost.setEntity(entity);
        HttpResponse response = httpclient.execute(httpPost);
        //String result = EntityUtils.toString(response.getEntity());
        HttpEntity result = response.getEntity();

        BufferedInputStream bis = new BufferedInputStream(result.getContent());
        String filePath = System.getProperty("user.dir") + tempFile;
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filePath)));
        int inByte;
        while ((inByte = bis.read()) != -1) {
            bos.write(inByte);
        }
        bis.close();
        bos.close();

        executeOnCommandLine("afplay " + System.getProperty("user.dir") + "/" + tempFile);
    } catch (Exception ex) {
        System.err.println(ex.getMessage());

    }
}

From source file:aiai.ai.core.ExecProcessService.java

public Result execCommand(List<String> cmd, File execDir, File consoleLogFile)
        throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder();
    pb.command(cmd);//w w  w. ja v  a  2s  . c o m
    pb.directory(execDir);
    pb.redirectErrorStream(true);
    final Process process = pb.start();

    final StreamHolder streamHolder = new StreamHolder();
    int exitCode;
    try (final FileOutputStream fos = new FileOutputStream(consoleLogFile);
            BufferedOutputStream bos = new BufferedOutputStream(fos)) {
        final Thread reader = new Thread(() -> {
            try {
                streamHolder.is = process.getInputStream();
                int c;
                while ((c = streamHolder.is.read()) != -1) {
                    bos.write(c);
                }
            } catch (IOException e) {
                log.error("Error collect data from output stream", e);
            }
        });
        reader.start();

        exitCode = process.waitFor();
        reader.join();
    } finally {
        try {
            if (streamHolder.is != null) {
                streamHolder.is.close();
            }
        } catch (Throwable th) {
            log.warn("Error with closing InputStream", th);
        }
    }

    log.info("Any errors of execution? {}", (exitCode == 0 ? "No" : "Yes"));
    log.debug("'\tcmd: {}", cmd);
    log.debug("'\texecDir: {}", execDir.getPath());
    String console = readLastLines(500, consoleLogFile);
    log.debug("'\tconsole output:\n{}", console);

    return new Result(exitCode == 0, exitCode, console);
}

From source file:com.elasticgrid.storage.amazon.s3.S3Storable.java

public File asFile() throws IOException {
    File f = File.createTempFile("elastic-grid-storable", getName());
    InputStream input = null;//w  w w.  j  a  v  a 2 s  .c o  m
    OutputStream output = null;
    try {
        input = asInputStream();
        output = new BufferedOutputStream(new FileOutputStream(f));
        IOUtils.copy(input, output);
    } finally {
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(output);
    }
    return f;
}

From source file:edu.umd.cs.buildServer.util.IO.java

/**
 * Read file from HTTP response body into a file.
 *
 * @param file/*  www  .j  ava  2  s.c o  m*/
 *            a File in the filesystem where the file should be stored
 * @param method
 *            the HttpMethod representing the request and response
 * @throws IOException
 *             if the complete file couldn't be downloaded
 */
public static void download(File file, HttpMethod method) throws IOException {
    InputStream in = null;
    OutputStream out = null;

    try {
        in = new BufferedInputStream(method.getResponseBodyAsStream());
        out = new BufferedOutputStream(new FileOutputStream(file));

        CopyUtils.copy(in, out);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:com.sangupta.jerry.util.ZipUtils.java

/**
 * Read a given file from the ZIP file and store it in a temporary file. The
 * temporary file is set to be deleted on exit of application.
 * /*ww w.  j  a v a  2s.  c o  m*/
 * @param zipFile
 *            the zip file from which the file needs to be read
 * 
 * @param fileName
 *            the name of the file that needs to be extracted
 * 
 * @return the {@link File} handle for the extracted file in the temp
 *         directory
 * 
 * @throws IllegalArgumentException
 *             if the zipFile is <code>null</code> or the fileName is
 *             <code>null</code> or empty.
 */
public static File readFileFromZip(File zipFile, String fileName) throws FileNotFoundException, IOException {
    if (zipFile == null) {
        throw new IllegalArgumentException("zip file to extract from cannot be null");
    }

    if (AssertUtils.isEmpty(fileName)) {
        throw new IllegalArgumentException("the filename to extract cannot be null/empty");
    }

    LOGGER.debug("Reading {} from {}", fileName, zipFile.getAbsolutePath());

    ZipInputStream stream = null;
    BufferedOutputStream outStream = null;
    File tempFile = null;

    try {
        byte[] buf = new byte[1024];
        stream = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry entry;
        while ((entry = stream.getNextEntry()) != null) {
            String entryName = entry.getName();
            if (entryName.equals(fileName)) {
                tempFile = File.createTempFile(FilenameUtils.getName(entryName),
                        FilenameUtils.getExtension(entryName));
                tempFile.deleteOnExit();

                outStream = new BufferedOutputStream(new FileOutputStream(tempFile));
                int readBytes;
                while ((readBytes = stream.read(buf, 0, 1024)) > -1) {
                    outStream.write(buf, 0, readBytes);
                }

                stream.close();
                outStream.close();

                return tempFile;
            }
        }
    } finally {
        IOUtils.closeQuietly(stream);
        IOUtils.closeQuietly(outStream);
    }

    return tempFile;
}

From source file:org.iti.agrimarket.view.FileUploadController.java

public String handleFileUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file,
        RedirectAttributes redirectAttributes) {
    if (name.contains("/")) {
        redirectAttributes.addFlashAttribute("message", "Folder separators not allowed");
        return "redirect:/";
    }//ww  w .j  av  a 2  s  . com
    if (name.contains("/")) {
        redirectAttributes.addFlashAttribute("message", "Relative pathnames not allowed");
        return "redirect:/";
    }

    if (!file.isEmpty()) {
        try {
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(name)));
            FileCopyUtils.copy(file.getInputStream(), stream);
            stream.close();
            redirectAttributes.addFlashAttribute("message", "You successfully uploaded " + name + "!");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("message",
                    "You failed to upload " + name + " => " + e.getMessage());
        }
    } else {
        redirectAttributes.addFlashAttribute("message",
                "You failed to upload " + name + " because the file was empty");
    }

    return "redirect:/index";
}

From source file:de.betterform.agent.web.servlet.XFormsRequestURIServlet.java

/**
 * This servlet uses the requestURI to locate and parse a XForms document for processing. The actual processing
 * is done by XFormsFilter. The parsed DOM of the document is passed as a request param to the filter.
 *
 * @param request  servlet request// ww  w .j av  a  2s  .  co m
 * @param response servlet response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    LOGGER.debug("hit XFormsRequestURIServlet");

    request.setCharacterEncoding("UTF-8");
    WebUtil.nonCachingResponse(response);

    Document doc;

    //locate it
    String formRequestURI = request.getRequestURI().substring(request.getContextPath().length() + 1);
    String realPath = null;
    try {
        realPath = WebFactory.getRealPath(formRequestURI, getServletContext());
    } catch (XFormsConfigException e) {
        throw new ServletException(e);
    }
    File xfDoc = new File(realPath);

    if (request.getHeader("betterform-internal") != null) {
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(xfDoc));
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());

        int read;
        while ((read = in.read()) > -1) {
            out.write(read);
        }
        out.flush();
    } else {
        try {
            //parse it
            doc = DOMUtil.parseXmlFile(xfDoc, true, false);
        } catch (ParserConfigurationException e) {
            throw new ServletException(e);
        } catch (SAXException e) {
            throw new ServletException(e);
        }

        request.setAttribute(WebFactory.XFORMS_NODE, doc);
        //do the Filter twist
        response.getOutputStream().close();
    }
}

From source file:adams.core.io.LzmaUtils.java

/**
 * Decompresses the specified lzma archive.
 *
 * @param archiveFile   the lzma file to decompress
 * @param buffer   the buffer size to use
 * @param outputFile   the destination file
 * @return      the error message, null if everything OK
 *///  www.jav a 2s  . c  om
@MixedCopyright(copyright = "Julien Ponge", license = License.APACHE2, url = "https://github.com/jponge/lzma-java/blob/master/README.md")
public static String decompress(File archiveFile, int buffer, File outputFile) {
    String result;
    LzmaInputStream in;
    OutputStream out;
    FileInputStream fis;
    FileOutputStream fos;
    String msg;

    in = null;
    fis = null;
    out = null;
    fos = null;
    result = null;
    try {

        // does file already exist?
        if (outputFile.exists())
            System.err.println("WARNING: overwriting '" + outputFile + "'!");

        fis = new FileInputStream(archiveFile.getAbsolutePath());
        in = new LzmaInputStream(new BufferedInputStream(fis), new Decoder());
        fos = new FileOutputStream(outputFile.getAbsolutePath());
        out = new BufferedOutputStream(fos);

        IOUtils.copy(in, out, buffer);
    } catch (Exception e) {
        msg = "Failed to decompress '" + archiveFile + "': ";
        System.err.println(msg);
        e.printStackTrace();
        result = msg + e;
    } finally {
        FileUtils.closeQuietly(in);
        FileUtils.closeQuietly(fis);
        FileUtils.closeQuietly(out);
        FileUtils.closeQuietly(fos);
    }

    return result;
}

From source file:com.esofthead.mycollab.module.file.service.impl.FileRawContentServiceImpl.java

@Override
public void saveContent(String objectPath, InputStream stream) {
    int startFileNameIndex = objectPath.lastIndexOf("/");
    if (startFileNameIndex > 0) {
        /*//from  w ww.j  ava  2s  .  co  m
        * make sure the directory exist
        */
        String folderPath = objectPath.substring(0, startFileNameIndex);
        File file = new File(baseFolder, folderPath);
        if (!file.exists() && !file.mkdirs()) {
            throw new MyCollabException("Create directory fail");
        }
    }

    try (BufferedOutputStream outStream = new BufferedOutputStream(
            new FileOutputStream(new File(baseFolder, objectPath)))) {
        byte[] buffer = new byte[BUFFER_SIZE];
        int byteRead;

        while ((byteRead = stream.read(buffer)) >= 0) {
            outStream.write(buffer, 0, byteRead);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

From source file:com.goodhuddle.huddle.service.impl.file.FileStoreImpl.java

@Override
public File createFile(String directoryName, String fileName, byte[] data) throws IOException {

    File file = createFile(directoryName, fileName);
    try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file))) {
        stream.write(data);/*from   w  w w  .java 2 s .com*/
    }
    return file;
}