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:com.glaf.core.util.ZipUtils.java

public static void unzip(java.io.InputStream inputStream, String dir) throws Exception {
    File file = new File(dir);
    FileUtils.mkdirsWithExistsCheck(file);
    ZipInputStream zipInputStream = null;
    FileOutputStream fileoutputstream = null;
    BufferedOutputStream bufferedoutputstream = null;
    try {// w ww .j  a  va 2s .c o  m
        zipInputStream = new ZipInputStream(inputStream);

        java.util.zip.ZipEntry zipEntry;
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            boolean isDirectory = zipEntry.isDirectory();
            byte abyte0[] = new byte[BUFFER];
            String s1 = zipEntry.getName();

            s1 = convertEncoding(s1);

            String s2 = dir + sp + s1;
            s2 = FileUtils.getJavaFileSystemPath(s2);

            if (s2.indexOf('/') != -1 || isDirectory) {
                String s4 = s2.substring(0, s2.lastIndexOf('/'));
                File file2 = new File(s4);
                FileUtils.mkdirsWithExistsCheck(file2);
            }
            if (isDirectory) {
                continue;
            }
            fileoutputstream = new FileOutputStream(s2);
            bufferedoutputstream = new BufferedOutputStream(fileoutputstream, BUFFER);
            int i = 0;
            while ((i = zipInputStream.read(abyte0, 0, BUFFER)) != -1) {
                bufferedoutputstream.write(abyte0, 0, i);
            }
            bufferedoutputstream.flush();
            IOUtils.closeStream(fileoutputstream);
            IOUtils.closeStream(bufferedoutputstream);
        }

    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(zipInputStream);
        IOUtils.closeStream(fileoutputstream);
        IOUtils.closeStream(bufferedoutputstream);
    }
}

From source file:com.esri.gpt.agp.multipart2.MPart.java

/**
 * Stream data from an input to an output.
 * @param source the input stream/*  w  w w  .  j  av  a 2  s . c o  m*/
 * @param destination the output stream
 * @throws IOException if an exception occurs
 */
protected long streamData(InputStream source, OutputStream destination) throws IOException {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        byte buffer[] = new byte[4096];
        int nRead = 0;
        int nMax = buffer.length;
        long nTotal = 0;
        bis = new BufferedInputStream(source);
        bos = new BufferedOutputStream(destination);
        while ((nRead = bis.read(buffer, 0, nMax)) >= 0) {
            bos.write(buffer, 0, nRead);
            nTotal += nRead;
        }
        return nTotal;
    } finally {
        try {
            if (bos != null)
                bos.flush();
        } catch (Exception ef) {
        }
    }
}

From source file:com.yunmel.syncretic.utils.io.IOUtils.java

/**
 * (??)/*from w  w  w  .  j  a v a  2  s.  c o  m*/
 * 
 * @param response
 * @param is ?
 * @param realName ??
 */
public static void downloadFile(HttpServletResponse response, InputStream is, String realName) {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        response.setContentType("text/html;charset=UTF-8");
        // request.setCharacterEncoding("UTF-8");
        long fileLength = is.available();

        response.setContentType("application/octet-stream");
        realName = new String(realName.getBytes("GBK"), "ISO8859-1");
        response.setHeader("Content-disposition", "attachment; filename=" + realName);
        response.setHeader("Content-Length", String.valueOf(fileLength));
        bis = new BufferedInputStream(is);
        bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[2048];
        int bytesRead;
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
    } catch (Exception e) {
        // e.printStackTrace();//???
    } finally {
        try {
            bos.close();
            bis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:de.climbingguide.erzgebirsgrenzgebiet.downloader.DownloaderThread.java

private Boolean ftpDownload(String ftpServer, String ftpPathName, String dateiname) {
    String fileName;/*from   w  w w.  j ava 2s .c o m*/
    Message msg;
    try {
        ftpConnect(ftpServer, "anonymous", "", 21);

        fileName = KleFuEntry.DOWNLOAD_LOCAL_DIRECTORY;
        File file = new File(fileName);
        file.mkdirs();
        fileName = fileName + dateiname;

        FTPFile[] ftpfile = mFTPClient.listFiles(ftpPathName);
        long fileSize = ftpfile[0].getSize();

        // notify download start
        int fileSizeInKB = (int) (fileSize / 1024);
        msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_DOWNLOAD_STARTED, fileSizeInKB, 0, fileName);
        activityHandler.sendMessage(msg);

        BufferedInputStream inStream = new BufferedInputStream(mFTPClient.retrieveFileStream(ftpPathName));
        File outFile = new File(fileName);
        FileOutputStream fileStream = new FileOutputStream(outFile);
        BufferedOutputStream outStream = new BufferedOutputStream(fileStream, KleFuEntry.DOWNLOAD_BUFFER_SIZE);
        byte[] data = new byte[KleFuEntry.DOWNLOAD_BUFFER_SIZE];
        int bytesRead = 0, totalRead = 0;

        while (!isInterrupted() && (bytesRead = inStream.read(data, 0, data.length)) >= 0) {
            outStream.write(data, 0, bytesRead);

            // update progress bar
            totalRead += bytesRead;
            int totalReadInKB = totalRead / 1024;
            msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_UPDATE_PROGRESS_BAR, totalReadInKB, 0);
            activityHandler.sendMessage(msg);
        }

        outStream.close();
        fileStream.close();
        inStream.close();

        if (isInterrupted()) {
            // the download was canceled, so let's delete the partially downloaded file
            outFile.delete();
            ftpDisconnect();
            return false;
        } else {
            ftpDisconnect();
            return true;
        }
    } catch (Exception e) {
        String errMsg = parentActivity.getString(R.string.error_message_general);
        msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_ENCOUNTERED_ERROR, 0, 0, errMsg);
        activityHandler.sendMessage(msg);
        return false;
    }
}

From source file:de.climbingguide.erzgebirsgrenzgebiet.downloader.DownloaderThread.java

private Boolean httpDownload(String downloadUrl, String dateiname) {
    URL url;//from  w ww .  j  a v a 2  s. co m
    URLConnection conn;
    String fileName;
    Message msg;
    try {
        url = new URL(downloadUrl);
        conn = url.openConnection();
        conn.setUseCaches(false);
        int fileSize = conn.getContentLength();

        fileName = KleFuEntry.DOWNLOAD_LOCAL_DIRECTORY;
        File file = new File(fileName);
        file.mkdirs();
        fileName = fileName + dateiname;

        // notify download start
        int fileSizeInKB = (int) (fileSize / 1024);
        msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_DOWNLOAD_STARTED, fileSizeInKB, 0, fileName);
        activityHandler.sendMessage(msg);

        BufferedInputStream inStream = new BufferedInputStream(conn.getInputStream());
        File outFile = new File(fileName);
        FileOutputStream fileStream = new FileOutputStream(outFile);
        BufferedOutputStream outStream = new BufferedOutputStream(fileStream, KleFuEntry.DOWNLOAD_BUFFER_SIZE);
        byte[] data = new byte[KleFuEntry.DOWNLOAD_BUFFER_SIZE];
        int bytesRead = 0, totalRead = 0;

        while (!isInterrupted() && (bytesRead = inStream.read(data, 0, data.length)) >= 0) {
            outStream.write(data, 0, bytesRead);

            // update progress bar
            totalRead += bytesRead;
            int totalReadInKB = totalRead / 1024;
            msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_UPDATE_PROGRESS_BAR, totalReadInKB, 0);
            activityHandler.sendMessage(msg);
        }

        outStream.close();
        fileStream.close();
        inStream.close();

        if (isInterrupted()) {
            // the download was canceled, so let's delete the partially downloaded file
            outFile.delete();
            return false;
        } else {
            return true;
        }
    } catch (Exception e) {
        String errMsg = parentActivity.getString(R.string.error_message_general);
        msg = Message.obtain(activityHandler, KleFuEntry.MESSAGE_ENCOUNTERED_ERROR, 0, 0, errMsg);
        activityHandler.sendMessage(msg);
        return false;
    }
}

From source file:cm.aptoide.pt.Aptoide.java

private void downloadServ(String srv) {
    try {/* w  w  w.ja  v a2  s  .co  m*/
        keepScreenOn.acquire();

        BufferedInputStream getit = new BufferedInputStream(new URL(srv).openStream());

        File file_teste = new File(TMP_SRV_FILE);
        if (file_teste.exists())
            file_teste.delete();

        FileOutputStream saveit = new FileOutputStream(TMP_SRV_FILE);
        BufferedOutputStream bout = new BufferedOutputStream(saveit, 1024);
        byte data[] = new byte[1024];

        int readed = getit.read(data, 0, 1024);
        while (readed != -1) {
            bout.write(data, 0, readed);
            readed = getit.read(data, 0, 1024);
        }

        keepScreenOn.release();

        bout.close();
        getit.close();
        saveit.close();
    } catch (Exception e) {
        AlertDialog p = new AlertDialog.Builder(this).create();
        p.setTitle(getText(R.string.top_error));
        p.setMessage(getText(R.string.aptoide_error));
        p.setButton(getText(R.string.btn_ok), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                return;
            }
        });
        p.show();
    }
}

From source file:com.dsh105.commodus.data.Updater.java

/**
 * Part of Zip-File-Extractor, modified by Gravity for use with Bukkit
 *//* ww  w. ja  va  2  s  . com*/
private void unzip(String file) {
    try {
        final File fSourceZip = new File(file);
        final String zipPath = file.substring(0, file.length() - 4);
        ZipFile zipFile = new ZipFile(fSourceZip);
        Enumeration<? extends ZipEntry> e = zipFile.entries();
        while (e.hasMoreElements()) {
            ZipEntry entry = e.nextElement();
            File destinationFilePath = new File(zipPath, entry.getName());
            destinationFilePath.getParentFile().mkdirs();
            if (entry.isDirectory()) {
                continue;
            } else {
                final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                int b;
                final byte buffer[] = new byte[Updater.BYTE_SIZE];
                final FileOutputStream fos = new FileOutputStream(destinationFilePath);
                final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE);
                while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) {
                    bos.write(buffer, 0, b);
                }
                bos.flush();
                bos.close();
                bis.close();
                final String name = destinationFilePath.getName();
                if (name.endsWith(".jar") && this.pluginFile(name)) {
                    destinationFilePath.renameTo(
                            new File(this.plugin.getDataFolder().getParent(), this.updateFolder + "/" + name));
                }
            }
            entry = null;
            destinationFilePath = null;
        }
        e = null;
        zipFile.close();
        zipFile = null;

        // Move any plugin data folders that were included to the right place, Bukkit won't do this for us.
        for (final File dFile : new File(zipPath).listFiles()) {
            if (dFile.isDirectory()) {
                if (this.pluginFile(dFile.getName())) {
                    final File oFile = new File(this.plugin.getDataFolder().getParent(), dFile.getName()); // Get current dir
                    final File[] contents = oFile.listFiles(); // List of existing files in the current dir
                    for (final File cFile : dFile.listFiles()) // Loop through all the files in the new dir
                    {
                        boolean found = false;
                        for (final File xFile : contents) // Loop through contents to see if it exists
                        {
                            if (xFile.getName().equals(cFile.getName())) {
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            // Move the new file into the current dir
                            cFile.renameTo(new File(oFile.getCanonicalFile() + "/" + cFile.getName()));
                        } else {
                            // This file already exists, so we don't need it anymore.
                            cFile.delete();
                        }
                    }
                }
            }
            dFile.delete();
        }
        new File(zipPath).delete();
        fSourceZip.delete();
    } catch (final IOException ex) {
        this.plugin.getLogger()
                .warning("The auto-updater tried to unzip a new update file, but was unsuccessful.");
        this.result = Updater.UpdateResult.FAIL_DOWNLOAD;
        ex.printStackTrace();
    }
    new File(file).delete();
}

From source file:edu.ku.brc.helpers.HTTPGetter.java

/**
 * Performs a "generic" HTTP request and fill member variable with results
 * use "getDigirResultsetStr" to get the results as a String
 *
 * @param url URL to be executed/*from  www  . j a  v  a2s .  co m*/
 * @param fileCache the file to place the results
 * @return returns an error code
 */
public byte[] doHTTPRequest(final String url, final File fileCache) {
    byte[] bytes = null;
    Exception excp = null;
    status = ErrorCode.NoError;

    // Create an HttpClient with the MultiThreadedHttpConnectionManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());

    GetMethod method = null;
    try {
        method = new GetMethod(url);

        //log.debug("getting " + method.getURI()); //$NON-NLS-1$
        httpClient.executeMethod(method);

        // get the response body as an array of bytes
        long bytesRead = 0;
        if (fileCache == null) {
            bytes = method.getResponseBody();
            bytesRead = bytes.length;

        } else {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileCache));
            bytes = new byte[4096];
            InputStream ins = method.getResponseBodyAsStream();
            BufferedInputStream bis = new BufferedInputStream(ins);
            while (bis.available() > 0) {
                int numBytes = bis.read(bytes);
                if (numBytes > 0) {
                    bos.write(bytes, 0, numBytes);
                    bytesRead += numBytes;
                }
            }

            bos.flush();
            bos.close();

            bytes = null;
        }

        log.debug(bytesRead + " bytes read"); //$NON-NLS-1$

    } catch (ConnectException ce) {
        excp = ce;
        log.error(String.format("Could not make HTTP connection. (%s)", ce.toString())); //$NON-NLS-1$
        status = ErrorCode.HttpError;

    } catch (HttpException he) {
        excp = he;
        log.error(String.format("Http problem making request.  (%s)", he.toString())); //$NON-NLS-1$
        status = ErrorCode.HttpError;

    } catch (IOException ioe) {
        excp = ioe;
        log.error(String.format("IO problem making request.  (%s)", ioe.toString())); //$NON-NLS-1$
        status = ErrorCode.IOError;

    } catch (java.lang.IllegalArgumentException ioe) {
        excp = ioe;
        log.error(String.format("IO problem making request.  (%s)", ioe.toString())); //$NON-NLS-1$
        status = ErrorCode.IOError;

    } catch (Exception e) {
        excp = e;
        log.error("Error: " + e); //$NON-NLS-1$
        status = ErrorCode.Error;

    } finally {
        // always release the connection after we're done
        if (isThrowingErrors && status != ErrorCode.NoError) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(HTTPGetter.class, excp);
        }

        if (method != null)
            method.releaseConnection();
        //log.debug("Connection released"); //$NON-NLS-1$
    }

    if (listener != null) {
        if (status == ErrorCode.NoError) {
            listener.completed(this);
        } else {
            listener.completedWithError(this, status);
        }
    }

    return bytes;
}

From source file:com.amytech.android.library.views.imagechooser.threads.MediaProcessorThread.java

private void copyFileToDir() throws Exception {
    try {/*w  ww . j a  v  a2 s .  c om*/
        File file;
        file = new File(Uri.parse(filePath).getPath());
        File copyTo = new File(FileUtils.getDirectory(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:com.amytech.android.library.views.imagechooser.threads.MediaProcessorThread.java

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

        filePath = FileUtils.getDirectory(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;
    }
}