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:org.brandroid.openmanager.util.FileManager.java

/**
 * //from w  w  w  .  j a v a 2s  . co m
 * @param old      the file to be copied
 * @param newDir   the directory to move the file to
 * @return
 */
public int copyToDirectory(String old, String newDir) {
    final File old_file = new File(old);
    final File temp_dir = new File(newDir);
    final byte[] data = new byte[BUFFER];
    int read = 0;

    if (old_file.isFile() && temp_dir.isDirectory() && temp_dir.canWrite()) {
        String file_name = old.substring(old.lastIndexOf("/"), old.length());
        File cp_file = new File(newDir + file_name);
        if (cp_file.equals(old_file))
            return 0;

        try {
            BufferedInputStream i_stream = new BufferedInputStream(new FileInputStream(old_file));
            BufferedOutputStream o_stream = new BufferedOutputStream(new FileOutputStream(cp_file));

            while ((read = i_stream.read(data, 0, BUFFER)) != -1)
                o_stream.write(data, 0, read);

            o_stream.flush();
            i_stream.close();
            o_stream.close();

        } catch (FileNotFoundException e) {
            Log.e("FileNotFoundException", e.getMessage());
            return -1;

        } catch (IOException e) {
            Log.e("IOException", e.getMessage());
            return -1;
        }

    } else if (old_file.isDirectory() && temp_dir.isDirectory() && temp_dir.canWrite()) {
        String files[] = old_file.list();
        String dir = newDir + old.substring(old.lastIndexOf("/"), old.length());
        int len = files.length;

        if (!new File(dir).mkdir())
            return -1;

        for (int i = 0; i < len; i++)
            copyToDirectory(old + "/" + files[i], dir);

    } else if (!temp_dir.canWrite())
        return -1;

    return 0;
}

From source file:net.oualid.maven.plugins.SurefireDashboardPlugin.java

private void flushResource(String source, File dest) {
    dest.getParentFile().mkdirs();/*from   w  w  w  .  j av  a 2s.c  om*/
    BufferedOutputStream os = null;
    BufferedInputStream is = null;
    try {
        is = new BufferedInputStream(SurefireDashboardPlugin.class.getResourceAsStream(source));
        os = new BufferedOutputStream(new FileOutputStream(dest));
        IOUtils.copy(is, os);
    } catch (IOException e) {
        getLog().error("Cannot flush resource on file system", e);
    } finally {
        if (os != null) {
            try {
                os.flush();
                os.close();
            } catch (IOException e) {
                getLog().error("Cannot flush resource on file system", e);
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                getLog().error("Cannot flush resource on file system", e);
            }
        }
    }
}

From source file:org.digitalcampus.oppia.utils.FileUtils.java

public static boolean unzipFiles(String srcDirectory, String srcFile, String destDirectory) {
    try {/* w w w.  ja v  a 2s.c  o  m*/
        // first make sure that all the arguments are valid and not null
        if (srcDirectory == null) {
            return false;
        }
        if (srcFile == null) {
            return false;
        }
        if (destDirectory == null) {
            return false;
        }
        if (srcDirectory.equals("")) {
            return false;
        }
        if (srcFile.equals("")) {
            return false;
        }
        if (destDirectory.equals("")) {
            return false;
        }
        // now make sure that these directories exist
        File sourceDirectory = new File(srcDirectory);
        File sourceFile = new File(srcDirectory + File.separator + srcFile);
        File destinationDirectory = new File(destDirectory);

        if (!sourceDirectory.exists()) {
            return false;
        }
        if (!sourceFile.exists()) {
            return false;
        }
        if (!destinationDirectory.exists()) {
            return false;
        }

        // now start with unzip process
        BufferedOutputStream dest = null;

        FileInputStream fis = new FileInputStream(sourceFile);
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));

        ZipEntry entry = null;

        while ((entry = zis.getNextEntry()) != null) {
            String outputFilename = destDirectory + File.separator + entry.getName();

            createDirIfNeeded(destDirectory, entry);

            int count;

            byte data[] = new byte[BUFFER_SIZE];

            File f = new File(outputFilename);

            // write the file to the disk
            if (!f.isDirectory()) {
                FileOutputStream fos = new FileOutputStream(f);
                dest = new BufferedOutputStream(fos, BUFFER_SIZE);

                // this counter is a hack to prevent getting stuck when
                // installing corrupted or not fully downloaded course
                // packages
                // it will prevent any course being installed with files
                // larger than around 500kb
                int counter = 0;
                while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
                    dest.write(data, 0, count);
                    counter++;
                    if (counter > 5000) {
                        dest.flush();
                        dest.close();
                        return false;
                    }
                }

                // close the output streams
                dest.flush();
                dest.close();
            }
        }

        // we are done with all the files
        // close the zip file
        zis.close();

    } catch (Exception e) {
        if (!MobileLearning.DEVELOPER_MODE) {
            BugSenseHandler.sendException(e);
        } else {
            e.printStackTrace();
        }
        return false;
    }

    return true;
}

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

public String writeArray(ArrayList data) {
    try {//from w ww .  jav  a 2  s.  com
        String tmpFilePath = dataFilePath + UUID.randomUUID().toString();
        File write = new File(tmpFilePath);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(write, true));
        write.deleteOnExit();
        StringBuilder sb = new StringBuilder();
        for (Object value : data) {
            sb.append(String.format("%.10f", (Double) value));
            sb.append(",");
        }
        String line = sb.toString();
        line = line.substring(0, line.length() - 1);
        bos.write(line.getBytes());
        bos.flush();
        bos.close();
        return tmpFilePath;

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

From source file:com.viettel.dms.download.DownloadFile.java

/**
 * Copy from one stream to another.  Throws IOException in the event of error
 * (for example, SD card is full)/*  w w  w  . j  ava  2 s  . co  m*/
 * 
 * @param is         Input stream.
 * @param os         Output stream.
 * @param buffer      Temporary buffer to use for copy.
 * @param bufferSize   Size of temporary buffer, in bytes.
 */
public static void copyStream(BufferedInputStream is, BufferedOutputStream os, byte[] buffer, int bufferSize)
        throws IOException {
    int sizeDownloaded = 0;
    int percent = 0;
    try {
        for (;;) {
            int count = is.read(buffer, 0, bufferSize);
            if (count >= 0) {
                sizeDownloaded += count;
                percent = (int) ((float) (sizeDownloaded) / (float) (fileSize) * 100);
                VTLog.d("copyStream", "current count: " + count + " sizeDownloaded: " + sizeDownloaded
                        + " fileSize: " + fileSize + " percent: " + percent);
                if (percent > 98) {
                    percent = 98;
                }
                try {
                    Context ct = GlobalInfo.getInstance().getActivityContext();
                    if (ct != null && ct instanceof GlobalBaseActivity) {
                        ((GlobalBaseActivity) ct).updateProgressPercentDialog(percent);
                    }
                } catch (Exception e) {
                    VTLog.e("copyStream", "fail", e);
                }
            }
            if (count == -1) {
                break;
            }
            os.write(buffer, 0, count);
        }
        os.flush();
    } catch (IOException e) {
        throw e;
    }
}

From source file:org.apache.wiki.site.SiteGeneratorTest.java

/**
 * Writes the file with the given content.
 * // ww  w. ja  v a 2s  .c  o  m
 * @param filename where to write.
 * @param content what to write.
 */
void write(String filename, String content) {
    BufferedOutputStream bos = null;
    try {
        LOG.info("Attempting to write " + filename);
        File file = new File(filename);
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
        bos.write(content.getBytes());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    } finally {
        if (bos != null) {
            try {
                bos.flush();
                bos.close();
            } catch (IOException e) {
                LOG.error(e.getMessage(), e);
            }
        }
    }
}

From source file:it.readbeyond.minstrel.commander.Commander.java

private void copyFileFromAssetsWWW(String sourcePath, String destinationPath,
        final CallbackContext callbackContext) {
    String source = "www" + File.separator + sourcePath;
    String destination = this.normalizePath(destinationPath);
    try {//from  w  ww .jav a2 s . c om
        File d = new File(destination);

        // create parent directory, if not existing
        File destinationParent = d.getParentFile();
        destinationParent.mkdirs();

        // TODO check for write permission?
        // copy in chunks of 4 KB
        final int BUFFER = 4096;
        BufferedInputStream is = new BufferedInputStream(
                cordova.getActivity().getApplicationContext().getAssets().open(source));
        int numberOfBytesRead;
        byte data[] = new byte[BUFFER];
        FileOutputStream fos = new FileOutputStream(d);
        BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
        while ((numberOfBytesRead = is.read(data, 0, BUFFER)) > -1) {
            dest.write(data, 0, numberOfBytesRead);
        }
        dest.flush();
        dest.close();
        is.close();
        fos.close();
        callbackContext.success(MESSAGE_FILE_COPIED);

    } catch (Exception e) {
        callbackContext.success(MESSAGE_ERROR_WHILE_COPYING);
    }
}

From source file:org.efaps.esjp.archives.Archive_Base.java

/**
 * Check if access will be granted to the cmd to create a root node.
 *
 * @param _parameter Parameter as passed by the eFaps API
 * @return new Return/*from w  ww. j  a  v a2s  .  c  om*/
 * @throws EFapsException on error
 */
public Return createFromZip(final Parameter _parameter) throws EFapsException {
    final Context.FileParameter fileItem = Context.getThreadContext().getFileParameters().get("upload");
    if (fileItem != null) {
        try {
            final InputStream input = fileItem.getInputStream();
            final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(input));
            ZipEntry entry;
            final FileUtil fileUtil = new FileUtil();
            final List<File> files = new ArrayList<>();
            while ((entry = zis.getNextEntry()) != null) {
                int size;
                final byte[] buffer = new byte[2048];
                final File file = fileUtil.getFile(entry.getName());
                if (!file.isHidden()) {
                    files.add(file);
                    final FileOutputStream fos = new FileOutputStream(file);
                    final BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length);
                    while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
                        bos.write(buffer, 0, size);
                    }
                    bos.flush();
                    bos.close();
                }
            }
            for (final File file : files) {
                if (file.length() > 0) {
                    final Context.FileParameter fileTmp = new FileItem(file);
                    Context.getThreadContext().getFileParameters().put("upload", fileTmp);
                    _parameter.getParameters().put("name", new String[] { fileTmp.getName() });
                    create(_parameter);
                }
            }
        } catch (final IOException e) {
            throw new EFapsException(Archive_Base.class, "createFromZip", e);
        }
    }
    return new Return();
}

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 {/*ww w .j a v  a2 s . com*/
        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);
    }
}