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:io.syndesis.project.converter.DefaultProjectGeneratorTest.java

private Path generate(GenerateProjectRequest request, ProjectGeneratorProperties generatorProperties)
        throws IOException {
    try (InputStream is = new DefaultProjectGenerator(new ConnectorCatalog(CATALOG_PROPERTIES),
            generatorProperties, registry).generate(request)) {
        Path ret = Files.createTempDirectory("integration-runtime");
        try (TarArchiveInputStream tis = new TarArchiveInputStream(is)) {

            TarArchiveEntry tarEntry = tis.getNextTarEntry();
            // tarIn is a TarArchiveInputStream
            while (tarEntry != null) {// create a file with the same name as the tarEntry
                File destPath = new File(ret.toFile(), tarEntry.getName());
                if (tarEntry.isDirectory()) {
                    destPath.mkdirs();//from w  w  w  .j ava  2  s . c o  m
                } else {
                    destPath.getParentFile().mkdirs();
                    destPath.createNewFile();
                    byte[] btoRead = new byte[8129];
                    BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath));
                    int len = tis.read(btoRead);
                    while (len != -1) {
                        bout.write(btoRead, 0, len);
                        len = tis.read(btoRead);
                    }
                    bout.close();
                }
                tarEntry = tis.getNextTarEntry();
            }
        }
        return ret;
    }
}

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

/** not used any more
static class ShutdownTimerTask extends TimerTask {
// possibly could tie this timer with user activity
public void run() {/*  w ww.  j a va 2s .  co m*/
out.println ("Shutting down ePADD completely at time " +  formatDateLong(new GregorianCalendar()));
savedSystemOut.println ("Shutting down ePADD completely at time " +  formatDateLong(new GregorianCalendar()));
        
// maybe throw open a browser window to let user know muse is shutting down ??
System.exit(0); // kill the program
}
}
*/

// util methods
public static void copy_stream_to_file(InputStream is, String filename) throws IOException {
    int bufsize = 64 * 1024;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        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:dk.netarkivet.viewerproxy.ARCArchiveAccess.java

/**
 * Read an entire page body into some stream.
 *
 * @param content The stream to read the page from. Not closed afterwards.
 * @param out The stream to write the results to. Not closed afterwards.
 * @throws IOFailure If the underlying reads or writes fail
 *///from  w ww . j av a 2s.  c o  m
private void readPage(InputStream content, OutputStream out) {
    BufferedInputStream page = new BufferedInputStream(content);
    BufferedOutputStream responseOut = new BufferedOutputStream(out);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        byte[] buffer = new byte[Constants.IO_BUFFER_SIZE];
        int bytesRead;
        while ((bytesRead = page.read(buffer)) != -1) {
            baos.write(buffer, 0, bytesRead);
            responseOut.write(buffer, 0, bytesRead);
        }
        responseOut.flush();
        log.debug("pagecontents: ", new String(baos.toByteArray(), "UTF-8"));
    } catch (IOException e) {
        throw new IOFailure("Could not read or write data", e);
    }
}

From source file:com.erudika.para.storage.LocalFileStore.java

@Override
public String store(String path, InputStream data) {
    if (StringUtils.startsWith(path, File.separator)) {
        path = path.substring(1);/*w  w w.  j a v a 2s  .  c  o  m*/
    }
    if (StringUtils.isBlank(path)) {
        return null;
    }
    int maxFileSizeMBytes = Config.getConfigInt("para.localstorage.max_filesize_mb", 10);
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    try {
        if (data.available() > 0 && data.available() <= (maxFileSizeMBytes * 1024 * 1024)) {
            File f = new File(folder + File.separator + path);
            if (f.canWrite()) {
                fos = new FileOutputStream(f);
                bos = new BufferedOutputStream(fos);
                int read = 0;
                byte[] bytes = new byte[1024];
                while ((read = data.read(bytes)) != -1) {
                    bos.write(bytes, 0, read);
                }
                return f.getAbsolutePath();
            }
        }
    } catch (IOException e) {
        logger.error(null, e);
    } finally {
        try {
            fos.close();
            bos.close();
            data.close();
        } catch (IOException e) {
            logger.error(null, e);
        }
    }
    return null;
}

From source file:edu.harvard.i2b2.fhirserver.ws.FileServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Get requested file by path info.

    String requestedFile = request.getPathInfo();

    if (requestedFile.equals("/"))
        requestedFile = "/index.html";
    logger.trace("Got request:" + requestedFile);
    logger.trace("basePath:" + this.basePath);
    logger.trace("ffp:" + basePath + requestedFile);

    // Check if file is actually supplied to the request URI.
    //if (requestedFile == null) {
    // Do your thing if the file is not supplied to the request URI.
    // Throw an exception, or send 404, or show default/warning page, or just ignore it.
    //  response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
    //return;/*  w w  w.j  a  va  2s .c  om*/
    //}

    // Decode the file name (might contain spaces and on) and prepare file object.
    URL url = new URL(basePath + requestedFile);
    logger.trace("url:" + url);
    File file = FileUtils.toFile(url);
    logger.trace("searching for file:" + file.getAbsolutePath());

    // Check if file actually exists in filesystem.
    if (!file.exists()) {
        // Do your thing if the file appears to be non-existing.
        // Throw an exception, or send 404, or show default/warning page, or just ignore it.
        response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
        return;
    }

    // Get content type by filename.
    String contentType = getServletContext().getMimeType(file.getName());

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/text";
    }

    // Init servlet response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setContentType(contentType);
    response.setHeader("Content-Length", String.valueOf(file.length()));
    //  response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

    // Prepare streams.
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        // Open streams.
        input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
        output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

        // Write file contents to response.
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
}

From source file:m.c.m.proxyma.resource.ProxymaServletResponse.java

/**
 * This private method serilizes the response data into the passed http response.
 *
 * @param responseData the data to send/*from w  w  w .ja  v a2 s.  c o m*/
 * @param theResponse the response implementation to use to send the data
 * @return the status code of the operation.
 */
private int serializeAndSendResponseData(ProxymaResponseDataBean responseData,
        HttpServletResponse theResponse) {
    //set the returnCode
    int exitStatus = responseData.getStatus();
    theResponse.setStatus(exitStatus);

    //set all the headers of the response data into the http servlet response..
    log.finer("Sending headers..");
    Iterator<String> stringIterarot = responseData.getHeaderNames().iterator();
    String headerName = null;
    ProxymaHttpHeader header = null;
    Collection<ProxymaHttpHeader> multiHeader = null;
    while (stringIterarot.hasNext()) {
        headerName = stringIterarot.next();
        if (responseData.isMultipleHeader(headerName)) {
            //Process multiple values header.
            multiHeader = responseData.getMultivalueHeader(headerName);
            Iterator<ProxymaHttpHeader> headers = multiHeader.iterator();
            while (headers.hasNext()) {
                header = headers.next();
                theResponse.setHeader(header.getName(), header.getValue());
            }
        } else {
            //Process Sungle value header
            header = responseData.getHeader(headerName);
            theResponse.setHeader(header.getName(), header.getValue());
        }
    }

    //set the cookies into the http servlet response.
    log.finer("Sending cookies..");
    Iterator<Cookie> cookieIterator = responseData.getCookies().iterator();
    while (cookieIterator.hasNext()) {
        theResponse.addCookie(cookieIterator.next());
    }

    //Serialize the data of the ByteBuffer into the servlet response..
    if (responseData.getData() != null) {
        BufferedOutputStream bos = null;
        log.finer("Sending data..");
        try {
            bos = new BufferedOutputStream(theResponse.getOutputStream());
            ByteBufferReader data = ByteBufferFactory.createNewByteBufferReader(responseData.getData());
            byte[] buffer = new byte[WRITE_BUFFER_SIZE];
            int count;
            while ((count = data.readBytes(buffer, WRITE_BUFFER_SIZE)) >= 0)
                bos.write(buffer, 0, count);
        } catch (Exception e) {
            log.severe("Error in writing buffer data into the response!");
            e.printStackTrace();
            exitStatus = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        } finally {
            try {
                if (bos != null) {
                    bos.flush();
                    bos.close();
                }
            } catch (IOException e) {
                log.severe("Error closing response output buffer!");
                e.printStackTrace();
                exitStatus = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
            }
        }
    }
    return exitStatus;
}

From source file:de.unirostock.sems.caroweb.Converter.java

private void checkout(HttpServletRequest request, HttpServletResponse response, Path storage, String req)
        throws ServletException, IOException {
    Path target = storage.resolve(req).toAbsolutePath().normalize();
    if (!target.startsWith(storage) || !Files.exists(target)) {
        error(request, response, "you're not allowed to download that file.");
        return;/*from   www.  j a va 2  s .co m*/
    }

    try {
        String mime = target.toString().endsWith("omex") ? "application/zip"
                : "application/vnd.wf4ever.robundle+zip";

        response.reset();
        response.setBufferSize(CaRoWebutils.DEFAULT_BUFFER_SIZE);
        response.setContentType(mime);
        response.setHeader("Content-Length", String.valueOf(target.toFile().length()));
        response.setHeader("Content-Disposition", "attachment; filename=\"" + req + "\"");
        response.setHeader("Expires", CaRoWebutils.downloadDateFormater
                .format(new Date(System.currentTimeMillis() + CaRoWebutils.CACHE_TIME * 1000)));
        response.setHeader("Cache-Control", "max-age=" + CaRoWebutils.CACHE_TIME);
        response.setHeader("Last-Modified", CaRoWebutils.downloadDateFormater
                .format(new Date(Files.getLastModifiedTime(target).toMillis())));
        response.setHeader("ETag", GeneralTools.hash(target + "-" + Files.getLastModifiedTime(target)));

        BufferedInputStream input = new BufferedInputStream(new FileInputStream(target.toFile()),
                CaRoWebutils.DEFAULT_BUFFER_SIZE);
        BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream(),
                CaRoWebutils.DEFAULT_BUFFER_SIZE);

        // pass the stream to client
        byte[] buffer = new byte[CaRoWebutils.DEFAULT_BUFFER_SIZE];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }

        input.close();
        output.close();

        return;
    } catch (IOException e) {
        // whoops, that's our fault. shouldn't happen. hopefully.
        LOGGER.error("unable to dump file " + target + " (at least not in an expected form)");
    }
    error(request, response, "couldn't dump file");
}

From source file:com.haru.ui.image.workers.MediaProcessorThread.java

private void copyFileToDir() throws Exception {
    try {//from  ww  w  .  ja  v  a  2 s.  c  o m
        File file;
        file = new File(Uri.parse(filePath).getPath());
        File copyTo = new File(foldername + File.separator + file.getName());
        FileInputStream streamIn = new FileInputStream(file);
        BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(copyTo));
        byte[] buf = new byte[2048];
        int len;
        while ((len = streamIn.read(buf)) > 0) {
            outStream.write(buf, 0, len);
        }
        streamIn.close();
        outStream.close();
        filePath = copyTo.getAbsolutePath();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        throw new Exception("File not found");
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("Corrupt or deleted file???");
    }
}

From source file:net.sf.jvifm.model.FileModelManager.java

private void extractEntry(InputStream zi, File file) throws Exception {
    BufferedOutputStream bf = new BufferedOutputStream(new FileOutputStream(file));
    while (true) {
        int n = zi.read(buffer);
        if (n < 0)
            break;
        bf.write(buffer, 0, n);
    }/*from w  w  w . j a v a2s .  c om*/
    bf.close();
}

From source file:com.haru.ui.image.workers.MediaProcessorThread.java

protected void processContentProviderMedia(String path, String extension) throws Exception {
    checkExtension(Uri.parse(path));//from w  w w.j ava 2  s  .co  m
    try {
        InputStream inputStream = context.getContentResolver().openInputStream(Uri.parse(path));

        filePath = foldername + File.separator + Calendar.getInstance().getTimeInMillis() + extension;

        BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(filePath));
        byte[] buf = new byte[2048];
        int len;
        while ((len = inputStream.read(buf)) > 0) {
            outStream.write(buf, 0, len);
        }
        inputStream.close();
        outStream.close();
        process();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}