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.microsoft.tfs.core.clients.workitem.internal.files.AttachmentUpDownHelper.java

public static void download(final URL attachmentUrl, final File localTarget,
        final TFSTeamProjectCollection connection) throws DownloadException {
    final TaskMonitor taskMonitor = TaskMonitorService.getTaskMonitor();
    final HttpClient httpClient = connection.getHTTPClient();
    final GetMethod method = new GetMethod(attachmentUrl.toExternalForm());
    boolean cancelled = false;
    OutputStream outputStream = null;

    try {/*from w  w  w .  j ava  2  s  .co m*/
        final int statusCode = httpClient.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            throw new DownloadException(MessageFormat.format(
                    Messages.getString("AttachmentUpDownHelper.ServerReturnedHTTPStatusFormat"), //$NON-NLS-1$
                    Integer.toString(statusCode)));
        }

        taskMonitor.begin(Messages.getString("AttachmentUpDownHelper.Downloading"), //$NON-NLS-1$
                computeTaskSize(method.getResponseContentLength()));

        final InputStream input = method.getResponseBodyAsStream();
        outputStream = new FileOutputStream(localTarget);
        outputStream = new BufferedOutputStream(outputStream);

        final byte[] buffer = new byte[DOWNLOAD_BUFFER_SIZE];
        int len;
        long totalBytesDownloaded = 0;

        while ((len = input.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
            totalBytesDownloaded += len;
            taskMonitor.worked(1);
            taskMonitor.setCurrentWorkDescription(MessageFormat.format(
                    Messages.getString("AttachmentUpDownHelper.DownloadedCountBytesFormat"), //$NON-NLS-1$
                    totalBytesDownloaded));
            if (taskMonitor.isCanceled()) {
                cancelled = true;
                break;
            }
            Thread.sleep(10);
        }

    } catch (final Exception ex) {
        throw new DownloadException(ex);
    } finally {
        method.releaseConnection();
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (final IOException e) {
            }
        }
    }

    if (cancelled) {
        localTarget.delete();
    }
}

From source file:de.thb.ue.backend.service.AnswerImageService.java

@Override
public void addAnswerImage(Vote vote, MultipartFile answerImage, String evaluationID) {
    File imageFolder = new File(
            (workingDirectoryPath.isEmpty() ? "" : (workingDirectoryPath + File.separatorChar)) + evaluationID
                    + File.separatorChar + "images");
    try {/*from   w w  w  .  j a  v a  2  s.  c o  m*/
        if (!imageFolder.exists()) {
            FileUtils.forceMkdir(imageFolder);
        }
        BufferedOutputStream stream = new BufferedOutputStream(
                new FileOutputStream(new File(imageFolder, vote.getId() + ".zip")));
        stream.write(answerImage.getBytes());
        stream.close();
    } catch (IOException e) {
        //TODO
        e.printStackTrace();
    }
}

From source file:com.t3.persistence.FileUtil.java

public static void saveResource(String resource, File destDir, String filename) throws IOException {
    File outFilename = new File(destDir + File.separator + filename);
    try (InputStream inStream = FileUtil.class.getClassLoader().getResourceAsStream(resource);
            BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(outFilename));) {
        IOUtils.copy(inStream, outStream);
    }//from w  w w  .  j a v a2  s  .  c  o  m
}

From source file:com.linkedin.thirdeye.bootstrap.util.TarGzCompressionUtils.java

/**
 * Creates a tar.gz file at the specified path with the contents of the
 * specified directory.//from ww  w .jav  a2  s .c  o m
 *
 * @param dirPath
 *          The path to the directory to create an archive of
 * @param archivePath
 *          The path to the archive to create
 *
 * @throws IOException
 *           If anything goes wrong
 */
public static void createTarGzOfDirectory(String directoryPath, String tarGzPath) throws IOException {
    FileOutputStream fOut = null;
    BufferedOutputStream bOut = null;
    GzipCompressorOutputStream gzOut = null;
    TarArchiveOutputStream tOut = null;

    try {
        fOut = new FileOutputStream(new File(tarGzPath));
        bOut = new BufferedOutputStream(fOut);
        gzOut = new GzipCompressorOutputStream(bOut);
        tOut = new TarArchiveOutputStream(gzOut);
        tOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
        addFileToTarGz(tOut, directoryPath, "");
    } finally {
        tOut.finish();

        tOut.close();
        gzOut.close();
        bOut.close();
        fOut.close();
    }
}

From source file:edu.ur.util.FileUtil.java

/**
 * Create a file in the specified directory with the
 * specified name and place in it the specified contents.
 *
 * @param directory - directory in which to create the file
 * @param fileName - name of the file to create
 * @param contents - Simple string to create the file
 *//*from w  w  w.  j a v  a2 s  .c  o m*/
public File creatFile(File directory, String fileName, String contents) {
    File f = new File(directory.getAbsolutePath() + IOUtils.DIR_SEPARATOR + fileName);

    // create the file
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;

    try {

        f.createNewFile();
        fos = new FileOutputStream(f);
        bos = new BufferedOutputStream(fos);

        bos.write(contents.getBytes());
        bos.flush();
        bos.close();
        fos.close();
    } catch (Exception e) {
        if (bos != null) {
            try {
                bos.close();
            } catch (Exception ec) {
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (Exception ec) {
            }
        }
        throw new RuntimeException(e);
    }

    return f;
}

From source file:com.kalai.controller.FileUploadController.java

@RequestMapping(value = "/fileupload", method = RequestMethod.POST)
public @ResponseBody String fileuploadstore(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file, ModelMap map) {
    if (!file.isEmpty()) {
        try {// ww  w  . j  a  va  2s .c o m
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(name)));
            stream.write(bytes);
            stream.close();
            map.addAttribute("uploadoption", "uploaded");
            map.addAttribute("Status", "uploaded Successfully" + name);

        } catch (Exception e) {
            map.addAttribute("uploadoption", "uploaded");
            map.addAttribute("Status", "uploaded UnSuccessfully" + name);
        }
    } else {
        map.addAttribute("Status", "uploaded  is Empty" + name);
    }
    return "fileupload";
}

From source file:net.sf.profiler4j.console.client.Client.java

public synchronized void connect(String host, int port) throws ClientException {
    try {/*from   w w w .  jav a2s . c  o m*/
        if (isConnected()) {
            throw new ClientException("Client already connected");
        }
        s = new Socket(host, port);
        out = new ObjectOutputStream(new BufferedOutputStream(s.getOutputStream()));
        in = new ObjectInputStream(new BufferedInputStream(s.getInputStream()));
        String serverVersion = in.readUTF();
        if (!serverVersion.equals(AgentConstants.VERSION)) {
            s.close();
            s = null;
            out = null;
            in = null;
            throw new ClientException("Version of remote agent is incompatible: console is '"
                    + AgentConstants.VERSION + "' but agent is '" + serverVersion + "'");
        }
        log.info("Client connected to " + host + ":" + port);
    } catch (Exception e) {
        handleException(e);
    }
    // fireClientEvent(new ClientEvent(this, ClientEvent.CONNECTED, null));
}

From source file:com.smartsheet.utils.HttpUtils.java

/**
 * Gets the JSON payload (as a String) returned by invoking HTTP GET on the
 * specified URL, with the optional accessToken and userToAssume arguments.
 *///from  w  w  w .  j  a v  a2 s.co m
public static String getJsonPayload(String url, String accessToken, String userToAssume) throws IOException {

    HttpGet httpGet = newGetRequest(url, accessToken, ACCEPT_JSON_HEADER, userToAssume);
    HttpResponse response = getResponse(httpGet);
    try {
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == ServiceUnavailableException.SERVICE_UNAVAILABLE_CODE)
            throw new ServiceUnavailableException(url);

        InputStream content = getContentOnSuccess(response, url, status);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        InputStream inStream = new BufferedInputStream(content);
        OutputStream outStream = new BufferedOutputStream(byteArrayOutputStream);
        copyAndClose(inStream, outStream);

        return byteArrayOutputStream.toString(CHARSET);

    } finally {
        httpGet.releaseConnection();
    }
}

From source file:com.usefullc.platform.common.utils.IOUtils.java

/**
 * // w  w  w .  ja  v  a  2s  . c  o m
 * 
 * @param path
 * @param fileName
 * @param response
 * @return
 */
public static void download(String path, String fileName, HttpServletResponse response) {
    try {

        if (StringUtils.isEmpty(path)) {
            throw new IllegalArgumentException("?");
        } else {
            File file = new File(path);
            if (!file.exists()) {
                throw new IllegalArgumentException("??");
            }
        }
        if (StringUtils.isEmpty(fileName)) {
            throw new IllegalArgumentException("???");
        }
        if (response == null) {
            throw new IllegalArgumentException("response ?");
        }

        // path
        File file = new File(path);

        // ??
        InputStream fis = new BufferedInputStream(new FileInputStream(path));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // response
        response.reset();

        // ??linux ?  linux utf-8,windows  GBK)
        String defaultEncoding = System.getProperty("file.encoding");
        if (defaultEncoding != null && defaultEncoding.equals("UTF-8")) {

            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("GBK"), "iso-8859-1"));
        } else {
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));
        }

        // responseHeader
        response.addHeader("Content-Length", "" + file.length());
        response.setContentType("application/octet-stream");
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.itbeyond.common.EOTrackMe.java

public static void removeSentLines(String lines) {
    int WriteLock_Timeout = 10;
    while (WriteLock_Timeout > 0) {
        try {// w w w. ja  va 2  s. com
            if (StringUtils.countMatches(lines, "|") == getLogFileLines()) {
                // Delete the log file
                EOTrackMe.getLogFile().delete();
            } else {
                File logFile = EOTrackMe.getLogFile();
                // We must remove already processed lines
                // As the file is appended
                String thisline;
                StringBuilder fullfile = new StringBuilder();
                BufferedReader br = new BufferedReader(new FileReader(logFile), 8192);
                while ((thisline = br.readLine()) != null) {
                    if (!StringUtils.contains(lines, thisline)) {
                        fullfile.append(thisline + "\n");
                    }
                }
                br.close();

                logFile.delete();
                logFile.createNewFile();

                FileOutputStream writer = new FileOutputStream(EOTrackMe.getLogFile(), false);
                BufferedOutputStream output = new BufferedOutputStream(writer);

                output.write(fullfile.toString().getBytes());
                output.flush();
                output.close();
            }
            break;
        } catch (IOException e) {
            if (WriteLock_Timeout < 5) {
                Utilities.LogError("EOTrackMe.removeSentLines - Write Lock", e);
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e1) {
            }
            WriteLock_Timeout -= 1;
        }
    }
}