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.dsh105.commodus.data.Updater.java

/**
 * Part of Zip-File-Extractor, modified by Gravity for use with Bukkit
 *//*from  www.ja  va2  s. c  om*/
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:com.ridgelineapps.wallpaper.photosite.TumblrUtils.java

void downloadPhoto(Photo photo, OutputStream destination) throws IOException {
    final BufferedOutputStream out = new BufferedOutputStream(destination, IO_BUFFER_SIZE);
    final String url = photo.getUrl();
    final HttpGet get = new HttpGet(url);

    HttpEntity entity = null;/*  w  w w .j a va 2s .co m*/
    try {
        final HttpResponse response = mClient.execute(get);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            entity = response.getEntity();
            entity.writeTo(out);
            out.flush();
        }
    } finally {
        if (entity != null) {
            entity.consumeContent();
        }
    }
}

From source file:org.apache.drill.exec.vector.complex.writer.TestJsonReader.java

License:asdf

@Test
public void testSumFilesWithDifferentSchema() throws Exception {
    String dfs_temp = getDfsTestTmpSchemaLocation();
    File table_dir = new File(dfs_temp, "multi_file");
    table_dir.mkdir();/*from   w  w w .  j a  v  a  2s .com*/
    BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(new File(table_dir, "a.json")));
    for (int i = 0; i < 10000; i++) {
        os.write("{ type : \"map\", data : { a : 1 } }\n".getBytes());
    }
    os.flush();
    os.close();
    os = new BufferedOutputStream(new FileOutputStream(new File(table_dir, "b.json")));
    for (int i = 0; i < 10000; i++) {
        os.write("{ type : \"bigint\", data : 1 }\n".getBytes());
    }
    os.flush();
    os.close();
    String query = "select sum(cast(case when `type` = 'map' then t.data.a else data end as bigint)) `sum` from dfs_test.tmp.multi_file t";
    try {
        testBuilder().sqlQuery(query).ordered()
                .optionSettingQueriesForTestQuery("alter session set `exec.enable_union_type` = true")
                .baselineColumns("sum").baselineValues(20000L).go();
    } finally {
        testNoResult("alter session set `exec.enable_union_type` = false");
    }
}

From source file:com.naryx.tagfusion.cfm.mail.cfPOP3.java

private void retrieveBody(cfSession _Session, Part Mess, cfQueryResultData popData, int Row, File attachmentDir)
        throws Exception {

    if (Mess.isMimeType("multipart/*")) {
        Multipart mp = (Multipart) Mess.getContent();
        int count = mp.getCount();
        for (int i = 0; i < count; i++)
            retrieveBody(_Session, mp.getBodyPart(i), popData, Row, attachmentDir);

    } else {// ww w .  j ava 2s. c om
        String filename = cfMailMessageData.getFilename(Mess);
        String dispos = Mess.getDisposition();

        // note: text/enriched shouldn't be treated as a text part of the email (see bug #2227)
        if ((dispos == null || dispos.equalsIgnoreCase(Part.INLINE)) && Mess.isMimeType("text/*")
                && !Mess.isMimeType("text/enriched")) {
            String content;
            String contentType = Mess.getContentType().toLowerCase();
            // support aliases of UTF-7 - UTF7, UNICODE-1-1-UTF-7, csUnicode11UTF7, UNICODE-2-0-UTF-7
            if (contentType.indexOf("utf-7") != -1 || contentType.indexOf("utf7") != -1) {
                content = new String(UTF7Converter.convert(readInputStream(Mess)));
            } else {
                try {
                    content = (String) Mess.getContent();
                } catch (UnsupportedEncodingException e) {
                    content = "Unable to retrieve message body due to UnsupportedEncodingException:"
                            + e.getMessage();
                } catch (ClassCastException e) {
                    // shouldn't happen but handle it gracefully
                    content = new String(readInputStream(Mess));
                }
            }

            if (Mess.isMimeType("text/html")) {
                popData.setCell(Row, 14, new cfStringData(content));
            } else if (Mess.isMimeType("text/plain")) {
                popData.setCell(Row, 15, new cfStringData(content));
            }
            popData.setCell(Row, 11, new cfStringData(content));

        } else if (attachmentDir != null) {

            File outFile;
            if (filename == null)
                filename = "unknownfile";

            outFile = getAttachedFilename(attachmentDir, filename,
                    getDynamic(_Session, "GENERATEUNIQUEFILENAMES").getBoolean());
            try {
                BufferedInputStream in = new BufferedInputStream(Mess.getInputStream());
                BufferedOutputStream out = new BufferedOutputStream(
                        cfEngine.thisPlatform.getFileIO().getFileOutputStream(outFile));
                IOUtils.copy(in, out);

                out.flush();
                out.close();
                in.close();

                //--[ Update the fields
                cfStringData cell = (cfStringData) popData.getCell(Row, 12);
                if (cell.getString().length() == 0)
                    cell = new cfStringData(filename);
                else
                    cell = new cfStringData(cell.getString() + "," + filename);

                popData.setCell(Row, 12, cell);

                cell = (cfStringData) popData.getCell(Row, 13);
                if (cell.getString().length() == 0)
                    cell = new cfStringData(outFile.toString());
                else
                    cell = new cfStringData(cell.getString() + "," + outFile.toString());

                popData.setCell(Row, 13, cell);

            } catch (Exception ignoreException) {
            }
        }
    }
}

From source file:com.bmc.gibraltar.automation.dataprovider.RestDataProvider.java

/**
 * Download file with the {@param attachmentName} name that was uploaded for the task
 *
 * @param taskGuid       task GUID//  ww w  . j  ava 2 s.com
 * @param attachmentName name of the file that was attached to the task
 * @return downloaded file
 */
@Step
public File getTaskAttachment(String taskGuid, String attachmentName) {
    LOG.info("Downloading an attachment with the name: " + attachmentName + " of the task with GUID: "
            + taskGuid);
    File downloadedFile = null;
    try {
        InputStream is = recordApi
                .getRecordInstanceContent(RestApiData.TASK_RECORD_DEFINITION, taskGuid, attachmentName)
                .extract().asInputStream();
        downloadedFile = new File(System.getProperty("java.io.tmpdir"), attachmentName);
        BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(downloadedFile));
        byte[] b = new byte[1024 * 1024];
        int read;
        while ((read = is.read(b)) > -1) {
            bout.write(b, 0, read);
        }
        bout.flush();
        bout.close();
        is.close();
    } catch (IOException e) {
        LOG.error("Cannot download a file " + attachmentName + " from server: " + e);
        e.printStackTrace();
    }
    return downloadedFile;
}

From source file:edu.dfci.cccb.mev.dataset.domain.gzip.GzipTsvInput.java

@Override
public InputStream input() throws IOException {
    if (log.isDebugEnabled())
        log.debug(url);/* w w w.  ja v  a 2 s  .  c  om*/

    GZIPInputStream zis = null;
    BufferedOutputStream dest = null;
    BufferedInputStream bis = null;
    File unzipped = new TemporaryFile();
    try {
        URLConnection urlc = url.openConnection();
        zis = new GZIPInputStream(urlc.getInputStream());

        int count;
        byte data[] = new byte[BUFFER];
        // write the files to the disk

        FileOutputStream fos = new FileOutputStream(unzipped);
        if (log.isDebugEnabled())
            log.debug("Unzipping SOFT file to " + unzipped.getAbsolutePath());

        dest = new BufferedOutputStream(fos, BUFFER);
        while ((count = zis.read(data, 0, BUFFER)) != -1) {
            dest.write(data, 0, count);
        }
        dest.flush();
        dest.close();
        return new FileInputStream(unzipped);

    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException ioe) {
            }
        }
        if (dest != null) {
            try {
                dest.close();
            } catch (IOException ioe) {
            }
        }
        if (zis != null) {
            try {
                zis.close();
            } catch (IOException ioe) {
            }
        }
    }

}

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

protected void processGooglePhotosMedia(String path, String extension) throws Exception {
    if (BuildConfig.DEBUG) {
        Log.i(TAG, "Google photos Started");
        Log.i(TAG, "URI: " + path);
        Log.i(TAG, "Extension: " + extension);
    }/*w  w  w  .  j a va  2  s.c o  m*/
    String retrievedExtension = checkExtension(Uri.parse(path));
    if (retrievedExtension != null && !TextUtils.isEmpty(retrievedExtension)) {
        extension = "." + retrievedExtension;
    }
    try {

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

        ParcelFileDescriptor parcelFileDescriptor = context.getContentResolver()
                .openFileDescriptor(Uri.parse(path), "r");

        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();

        InputStream inputStream = new FileInputStream(fileDescriptor);

        BufferedInputStream reader = new BufferedInputStream(inputStream);

        BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(filePath));
        byte[] buf = new byte[2048];
        int len;
        while ((len = reader.read(buf)) > 0) {
            outStream.write(buf, 0, len);
        }
        outStream.flush();
        outStream.close();
        inputStream.close();
        process();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    if (BuildConfig.DEBUG) {
        Log.i(TAG, "Picasa Done");
    }
}

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

/**
 * This will return the file from tgz file and store it in specified location.
 *
 * @param   tgzFileName is the name of tgz 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//from   w ww.j  a v  a 2 s .co m
 */
public static boolean extractFileFromTGZ(String tgzFileName, String fileName, String strDestLoc,
        boolean bFirstDirLevel) {

    boolean bRetCode = Constants.bFAILURE;

    TarArchiveInputStream tarIn = null;

    try {

        tarIn = new TarArchiveInputStream(
                new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(tgzFileName))));
    } catch (Exception e) {
        Utility.debugPrint(Constants.DEBUG_ERROR, "Exception in unzipping tar file: " + e);
        return bRetCode;
    }

    try {
        BufferedOutputStream bufOut = null;
        BufferedInputStream bufIn = null;
        TarArchiveEntry tarEntry = null;
        while ((tarEntry = tarIn.getNextTarEntry()) != null) {
            if (!tarEntry.getName().endsWith(fileName))
                continue;
            //Get file at root (in single directory) level. This is for License in root location.
            if (bFirstDirLevel && (tarEntry.getName().indexOf('/') != tarEntry.getName().lastIndexOf('/')))
                continue;
            bufIn = new BufferedInputStream(tarIn);
            int count;
            byte data[] = new byte[Constants.BUFFER];
            String strOutFileName = strDestLoc == null ? tarEntry.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.drill.exec.vector.complex.writer.TestJsonReader.java

License:asdf

@Test
public void drill_4032() throws Exception {
    String dfs_temp = getDfsTestTmpSchemaLocation();
    File table_dir = new File(dfs_temp, "drill_4032");
    table_dir.mkdir();/*  ww  w.j  a  v a  2  s .  c o m*/
    BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(new File(table_dir, "a.json")));
    os.write("{\"col1\": \"val1\",\"col2\": null}".getBytes());
    os.write("{\"col1\": \"val1\",\"col2\": {\"col3\":\"abc\", \"col4\":\"xyz\"}}".getBytes());
    os.flush();
    os.close();
    os = new BufferedOutputStream(new FileOutputStream(new File(table_dir, "b.json")));
    os.write("{\"col1\": \"val1\",\"col2\": null}".getBytes());
    os.write("{\"col1\": \"val1\",\"col2\": null}".getBytes());
    os.flush();
    os.close();
    testNoResult("select t.col2.col3 from dfs_test.tmp.drill_4032 t");
}

From source file:com.sqli.liferay.imex.util.xml.ZipUtils.java

public void _unzipArchive(File archive, File outputDir) throws IOException {
    BufferedOutputStream dest = null;
    FileInputStream fis = new FileInputStream(archive);
    CheckedInputStream checksum = new CheckedInputStream(fis, new Adler32());
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(checksum));
    ZipEntry entry;//from ww w. jav a  2s.co m
    while ((entry = zis.getNextEntry()) != null) {
        log.debug("Extracting: " + entry);
        int count;
        byte data[] = new byte[BUFFER];
        // write the files to the disk
        FileOutputStream fos = new FileOutputStream(entry.getName());
        dest = new BufferedOutputStream(fos, BUFFER);
        while ((count = zis.read(data, 0, BUFFER)) != -1) {
            dest.write(data, 0, count);
        }
        dest.flush();
        dest.close();
    }
    zis.close();
    log.debug("Checksum:" + checksum.getChecksum().getValue());

}