Example usage for java.io BufferedOutputStream flush

List of usage examples for java.io BufferedOutputStream flush

Introduction

In this page you can find the example usage for java.io BufferedOutputStream flush.

Prototype

@Override
public synchronized void flush() throws IOException 

Source Link

Document

Flushes this buffered output stream.

Usage

From source file:com.sogrey.sinaweibo.utils.FileUtil.java

/**
 * ?//w  ww .  j a va  2  s.c  o m
 * 
 * @author Sogrey
 * @date 2015630
 * @param sourceFile
 * @param targetFile
 */
public static void copyFile(File sourceFile, File targetFile) {

    try {
        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        try {
            // ?
            inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

            // ?
            outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

            // 
            byte[] b = new byte[1024 * 5];
            int len;
            while ((len = inBuff.read(b)) != -1) {
                outBuff.write(b, 0, len);
            }
            // ?
            outBuff.flush();
        } finally {
            // ?
            if (inBuff != null)
                inBuff.close();
            if (outBuff != null)
                outBuff.close();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.deeplearning4j.plot.NeuralNetPlotter.java

protected String writeMatrix(INDArray matrix) {
    try {//from w  ww .j a  va  2  s. c om
        String tmpFilePath = dataFilePath + UUID.randomUUID().toString();
        File write = new File(tmpFilePath);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(write, true));
        write.deleteOnExit();
        for (int i = 0; i < matrix.rows(); i++) {
            INDArray row = matrix.getRow(i);
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < row.length(); j++) {
                sb.append(String.format("%.10f", row.getDouble(j)));
                if (j < row.length() - 1)
                    sb.append(",");
            }
            sb.append("\n");
            String line = sb.toString();
            bos.write(line.getBytes());
            bos.flush();
        }
        bos.close();
        return tmpFilePath;

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

From source file:com.sogrey.sinaweibo.utils.FileUtil.java

/**
 * ?//from ww  w.j a v  a  2  s. com
 * 
 * @author Sogrey
 * @date 2015630
 * @param sourcePath
 * @param toPath
 */
public static void copyFile(String sourcePath, String toPath) {
    File sourceFile = new File(sourcePath);
    File targetFile = new File(toPath);
    createDipPath(toPath);
    try {
        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        try {
            // ?
            inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

            // ?
            outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

            // 
            byte[] b = new byte[1024 * 5];
            int len;
            while ((len = inBuff.read(b)) != -1) {
                outBuff.write(b, 0, len);
            }
            // ?
            outBuff.flush();
        } finally {
            // ?
            if (inBuff != null)
                inBuff.close();
            if (outBuff != null)
                outBuff.close();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:bammerbom.ultimatecore.bukkit.UltimateUpdater.java

/**
 * Part of Zip-File-Extractor, modified by Gravity for use with Updater.
 *
 * @param file the location of the file to extract.
 *//* ww w  .  j av a  2  s .co  m*/
private void unzip(String file) {
    final File fSourceZip = new File(file);
    try {
        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()) {
                final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                int b;
                final byte[] buffer = new byte[UltimateUpdater.BYTE_SIZE];
                final FileOutputStream fos = new FileOutputStream(destinationFilePath);
                final BufferedOutputStream bos = new BufferedOutputStream(fos, UltimateUpdater.BYTE_SIZE);
                while ((b = bis.read(buffer, 0, UltimateUpdater.BYTE_SIZE)) != -1) {
                    bos.write(buffer, 0, b);
                }
                bos.flush();
                bos.close();
                bis.close();
                final String name = destinationFilePath.getName();
                if (name.endsWith(".jar") && this.pluginExists(name)) {
                    File output = new File(updateFolder, name);
                    destinationFilePath.renameTo(output);
                }
            }
        }
        zipFile.close();

        // Move any plugin data folders that were included to the right place, Bukkit won't do this for us.
        moveNewZipFiles(zipPath);

    } catch (final IOException e) {
    } finally {
        fSourceZip.delete();
    }
}

From source file:com.sun.identity.security.cert.AMCRLStore.java

private byte[] getCRLByHttpURI(String url) {
    String argString = ""; //default
    StringBuffer params = null;/*from w ww.ja  va  2 s. c o m*/
    HttpURLConnection con = null;
    byte[] crl = null;

    String uriParamsCRL = storeParam.getURIParams();

    try {

        if (uriParamsCRL != null) {
            params = new StringBuffer();
            StringTokenizer st1 = new StringTokenizer(uriParamsCRL, ",");
            while (st1.hasMoreTokens()) {
                String token = st1.nextToken();
                StringTokenizer st2 = new StringTokenizer(token, "=");
                if (st2.countTokens() == 2) {
                    String param = st2.nextToken();
                    String value = st2.nextToken();
                    params.append(URLEncDec.encode(param) + "=" + URLEncDec.encode(value));
                } else {
                    continue;
                }

                if (st1.hasMoreTokens()) {
                    params.append("&");
                }
            }
        }

        URL uri = new URL(url);
        con = HttpURLConnectionManager.getConnection(uri);

        // Prepare for both input and output
        con.setDoInput(true);

        // Turn off Caching
        con.setUseCaches(false);

        if (params != null) {
            byte[] paramsBytes = params.toString().trim().getBytes("UTF-8");
            if (paramsBytes.length > 0) {
                con.setDoOutput(true);
                con.setRequestProperty("Content-Length", Integer.toString(paramsBytes.length));

                // Write the arguments as post data
                BufferedOutputStream out = new BufferedOutputStream(con.getOutputStream());
                out.write(paramsBytes, 0, paramsBytes.length);
                out.flush();
                out.close();
            }
        }
        // Input ...
        InputStream in = con.getInputStream();

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        int len;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf, 0, buf.length)) != -1) {
            bos.write(buf, 0, len);
        }
        crl = bos.toByteArray();

        if (debug.messageEnabled()) {
            debug.message("AMCRLStore.getCRLByHttpURI: crl.length = " + crl.length);
        }
    } catch (Exception e) {
        debug.error("getCRLByHttpURI : Error in getting CRL", e);
    }

    return crl;
}

From source file:com.amaze.filemanager.utils.files.GenericCopyUtil.java

private void copyFile(BufferedInputStream bufferedInputStream, BufferedOutputStream bufferedOutputStream)
        throws IOException {
    int count = 0;
    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];

    try {/*from   ww w  .  j  a  v a  2 s. c om*/
        while (count != -1) {

            count = bufferedInputStream.read(buffer);
            if (count != -1 && !progressHandler.getCancelled()) {

                bufferedOutputStream.write(buffer, 0, count);
                ServiceWatcherUtil.position += count;
            } else
                break;
        }
    } finally {
        bufferedOutputStream.flush();
    }
}

From source file:com.umeng.comm.ui.widgets.ImageBrowser.java

private void saveImage() {
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    try {/*from   w w  w.  j a v  a  2 s. com*/
        String url = mImageList.get(mViewPager.getCurrentItem()).middleImageUrl;
        String fileName = Md5Helper.toMD5(url);
        File imgFile = new File(getCacheDir() + File.separator + fileName + ".png");
        in = new BufferedInputStream(ImageCache.getInstance().getInputStream(fileName), 8 * 1024);
        out = new BufferedOutputStream(new FileOutputStream(imgFile), 8 * 1024);
        byte[] buffer = new byte[4 * 1024];
        int len = 0;
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        out.flush();
        galleryAddPic(imgFile);
        ToastMsg.showShortMsg(getContext(),
                ResFinder.getString("umeng_comm_save_pic_success") + imgFile.getAbsolutePath());
    } catch (FileNotFoundException e) {
        ToastMsg.showShortMsg(getContext(), ResFinder.getString("umeng_comm_save_pic_failed"));
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
        ToastMsg.showShortMsg(getContext(), ResFinder.getString("umeng_comm_save_pic_failed"));
    } finally {
        CommonUtils.closeSilently(out);
        CommonUtils.closeSilently(in);
    }
}

From source file:com.connection.factory.SftpConnectionApacheLib.java

@Override
public boolean downloadFile(String fullLocalPad, String fullRemotePath) {
    File file = new File(fullLocalPad);
    InputStream input = null;//  ww  w . j a  v a 2  s  . co  m
    BufferedOutputStream output = null;
    try {
        input = command.get(fullRemotePath);
        if (input == null) {
            return false;
        }
    } catch (SftpException ex) {
        if (file.exists()) {
            file.delete();
        }
        return false;
    }
    try {
        output = new BufferedOutputStream(new FileOutputStream(file));
        byte[] bytesArray = new byte[CURRENT_FILE_BYTE_BUFFER];
        int bytesRead = -1;
        while ((bytesRead = input.read(bytesArray)) != -1) {
            output.write(bytesArray, 0, bytesRead);
            output.flush();
        }

        output.close();
        input.close();
        return true;

    } catch (IOException ex) {
        if (file.exists()) {
            file.delete();
        }
        return false;
    }

}

From source file:org.apache.sysml.validation.ValidateLicAndNotice.java

/**
 * This will return the file from zip file and store it in specified location.
 *
 * @param   zipFileName is the name of zip file from which file to be extracted.
 * @param   fileName is the name of the file to be extracted.
 * @param   strDestLoc is the location where file will be extracted.
 * @param    bFirstDirLevel to indicate to get file from first directory level.
 * @return  Sucess or Failure//w  ww.  j  a  v a 2  s  .co  m
 */
public static boolean extractFileFromZip(String zipFileName, String fileName, String strDestLoc,
        boolean bFirstDirLevel) {
    boolean bRetCode = Constants.bFAILURE;
    try {
        BufferedOutputStream bufOut = null;
        BufferedInputStream bufIn = null;
        ZipEntry entry;
        ZipFile zipfile = new ZipFile(zipFileName);
        Enumeration e = zipfile.entries();
        while (e.hasMoreElements()) {
            entry = (ZipEntry) e.nextElement();
            if (!entry.getName().endsWith(fileName))
                continue;
            //Get file at root (in single directory) level. This is for License in root location.
            if (bFirstDirLevel && (entry.getName().indexOf('/') != entry.getName().lastIndexOf('/')))
                continue;
            bufIn = new BufferedInputStream(zipfile.getInputStream(entry));
            int count;
            byte data[] = new byte[Constants.BUFFER];
            String strOutFileName = strDestLoc == null ? entry.getName() : strDestLoc + "/" + fileName;
            FileOutputStream fos = new FileOutputStream(strOutFileName);
            bufOut = new BufferedOutputStream(fos, Constants.BUFFER);
            while ((count = bufIn.read(data, 0, Constants.BUFFER)) != -1) {
                bufOut.write(data, 0, count);
            }
            bufOut.flush();
            bufOut.close();
            bufIn.close();
            bRetCode = Constants.bSUCCESS;
            break;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return bRetCode;
}

From source file:org.apache.hadoop.hdfs.LocalReadWritePerf.java

/**
 * write a local dist file/*  w  w w  .java 2  s .  com*/
 */
private void writeLocalFile(File filePath, long sizeKB) throws IOException {
    BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(filePath));
    long fileSize = sizeKB * 1024;
    int bufSize = (int) Math.min(MAX_BUF_SIZE, fileSize);
    byte[] data = new byte[bufSize];
    long toWrite = fileSize;
    rand.nextBytes(data);
    while (toWrite > 0) {
        int len = (int) Math.min(toWrite, bufSize);
        os.write(data, 0, len);
        toWrite -= len;
    }
    os.flush();
    os.close();
}