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.apache.jackrabbit.standalone.cli.fs.ExportPropertyToFile.java

/**
 * Export th given value to a File/*w  w  w. j a v a 2 s . c o  m*/
 * @param ctx
 *        the <code>Context</code>
 * @param value
 *        the <code>Value</code>
 * @param to
 *        the target file system path
 * @throws CommandException
 *         if the <code>File</code> already exists
 * @throws IOException
 *         if an <code>IOException</code> occurs
 * @throws RepositoryException
 *         if the current working <code>Repository</code> throws an
 *         <code>Exception</code>
 */
private void exportValue(Context ctx, Value value, String to)
        throws CommandException, IOException, RepositoryException {
    boolean overwrite = Boolean.valueOf((String) ctx.get(this.overwriteKey)).booleanValue();

    File file = new File(to);

    // Check if there's a file at the given target path
    if (file.exists() && !overwrite) {
        throw new CommandException("exception.file.exists", new String[] { to });
    }

    // If it doesn't exists create the file
    if (!file.exists()) {
        file.createNewFile();
    }

    if (value.getType() == PropertyType.BINARY) {
        InputStream in = value.getStream();
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
        int c;
        while ((c = in.read()) != -1) {
            out.write(c);
        }
        in.close();
        out.flush();
        out.close();
    } else {
        Reader in = new StringReader(value.getString());
        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        int c;
        while ((c = in.read()) != -1) {
            out.write(c);
        }
        in.close();
        out.flush();
        out.close();
    }
}

From source file:com.m2team.phuotstory.activity.DirectionActivity.java

@OnClick(R.id.btn_choose)
public void done() {
    final Intent intent = new Intent(DirectionActivity.this, WriteActivity.class);
    intent.putExtra(Constant.ACTION_TYPE, Constant.TYPE_LOCATIONS);
    intent.putExtra(Constant.ARRAY_LOCATION, locations);
    intent.putExtra(Constant.TOTAL_DISTANCE, totalDistance / 1000);
    mMap.snapshot(new GoogleMap.SnapshotReadyCallback() {

        @Override/*w w  w.j  a v a 2 s .c  om*/
        public void onSnapshotReady(Bitmap bitmap) {
            if (bitmap != null) {
                File file = new File(getFilesDir() + "/" + System.currentTimeMillis() + ".jpg");
                final int BUFFER_SIZE = 1024 * 8;
                try {
                    file.createNewFile();
                    FileOutputStream fos = new FileOutputStream(file);
                    final BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER_SIZE);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                    bos.flush();
                    bos.close();
                    fos.close();
                    Applog.d(file.getAbsolutePath());
                    intent.putExtra(Constant.IMAGE_BITMAP_MAP, file.getAbsolutePath());

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            startActivity(intent);
            finish();
        }
    });
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.VoiceObj.java

@Override
public void activate(final Context context, final SignedObj obj) {
    Runnable r = new Runnable() {
        @Override//ww  w .  j a va2  s .  c o  m
        public void run() {
            byte[] bytes = obj.getRaw();
            if (bytes == null) {
                Pair<JSONObject, byte[]> p = splitRaw(obj.getJson());
                //                content = p.first;
                bytes = p.second;
            }

            /*AudioTrack track = new AudioTrack(AudioManager.STREAM_MUSIC, RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING, bytes.length, AudioTrack.MODE_STATIC);
            track.write(bytes, 0, bytes.length);
            try { // TODO: hack.
            Thread.sleep(500);
             } catch (InterruptedException e) {
             }
            track.play();
            */
            /****/

            File file = new File(getTempFilename());
            try {
                OutputStream os = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(os);
                bos.write(bytes, 0, bytes.length);
                bos.flush();
                bos.close();

                copyWaveFile(getTempFilename(), getFilename());
                deleteTempFile();

                MediaPlayer mp = new MediaPlayer();

                mp.setDataSource(getFilename());
                mp.prepare();
                mp.start();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
    if (context instanceof Activity) {
        ((Activity) context).runOnUiThread(r);
    } else {
        r.run();
    }
}

From source file:fr.gael.dhus.database.liquibase.CopyProductImagesBlobToFile.java

private void blobToFile(Blob blob, String out) {
    InputStream is = null;/*from w  ww  . ja v  a  2 s.c  o m*/
    OutputStream os = null;
    BufferedOutputStream bos = null;

    try {
        is = blob.getBinaryStream();
        os = new FileOutputStream(out);
        bos = new BufferedOutputStream(os);
        IOUtils.copy(is, bos);
        bos.flush();
    } catch (Exception e) {
        logger.error("Cannot copy blob into '" + out + "'.", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                logger.warn("Cannot close InputStream !");
            }
        }
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException e) {
                logger.warn("Cannot close BufferedOutputStream !");
            }
        }
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                logger.warn("Cannot close OutputStream !");
            }
        }
    }
}

From source file:org.ktunaxa.referral.server.mvc.UploadGeometryController.java

private URL unzipShape(byte[] fileContent) throws IOException {
    String tempDir = System.getProperty("java.io.tmpdir");

    URL url = null;//from   w w w .  j  a  v  a  2s.  c  o m
    ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(fileContent));
    try {
        ZipEntry entry;
        while ((entry = zin.getNextEntry()) != null) {
            log.info("Extracting: " + entry);
            String name = tempDir + "/" + entry.getName();
            tempFiles.add(name);
            if (name.endsWith(".shp")) {
                url = new URL("file://" + name);
            }
            int count;
            byte[] data = new byte[BUFFER];
            // write the files to the disk
            deleteFileIfExists(name);
            FileOutputStream fos = new FileOutputStream(name);
            BufferedOutputStream destination = new BufferedOutputStream(fos, BUFFER);
            try {
                while ((count = zin.read(data, 0, BUFFER)) != -1) {
                    destination.write(data, 0, count);
                }
                destination.flush();
            } finally {
                destination.close();
            }
        }
    } finally {
        zin.close();
    }
    if (url == null) {
        throw new IllegalArgumentException("Missing .shp file");
    }
    return url;
}

From source file:edu.uci.ics.asterix.event.service.AsterixEventServiceUtil.java

public static void unzip(String sourceFile, String destDir) throws IOException {
    BufferedOutputStream dest = null;
    FileInputStream fis = new FileInputStream(sourceFile);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
    ZipEntry entry = null;//from www.j  a  va2  s .  co  m

    int BUFFER_SIZE = 4096;
    while ((entry = zis.getNextEntry()) != null) {
        String dst = destDir + File.separator + entry.getName();
        if (entry.isDirectory()) {
            createDir(destDir, entry);
            continue;
        }
        int count;
        byte data[] = new byte[BUFFER_SIZE];

        // write the file to the disk
        FileOutputStream fos = new FileOutputStream(dst);
        dest = new BufferedOutputStream(fos, BUFFER_SIZE);
        while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
            dest.write(data, 0, count);
        }
        // close the output streams
        dest.flush();
        dest.close();
    }

    zis.close();
}

From source file:edu.stanford.mobisocial.dungbeetle.obj.action.PlayAllAudioAction.java

public void playNextSong() {
    if (c.isAfterLast()) {
        c.close();//  w w  w. ja va  2 s. co  m
        alert.dismiss();
        return;
    }

    try {
        final JSONObject objData = new JSONObject(c.getString(c.getColumnIndex(DbObject.JSON)));
        Runnable r = new Runnable() {
            @Override
            public void run() {

                Log.w("PlayAllAudioAction", objData.optString("feedName"));
                byte bytes[] = Base64.decode(objData.optString(VoiceObj.DATA), Base64.DEFAULT);

                File file = new File(getTempFilename());
                try {
                    OutputStream os = new FileOutputStream(file);
                    BufferedOutputStream bos = new BufferedOutputStream(os);
                    bos.write(bytes, 0, bytes.length);
                    bos.flush();
                    bos.close();

                    copyWaveFile(getTempFilename(), getFilename());
                    deleteTempFile();

                    mp = new MediaPlayer();

                    mp.setDataSource(getFilename());
                    mp.setOnCompletionListener(new OnCompletionListener() {

                        public void onCompletion(MediaPlayer m) {
                            Log.w("PlayAllAudioAction", "finished");
                            c.moveToNext();
                            playNextSong();
                        }
                    });
                    mp.prepare();
                    mp.start();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        if (context instanceof Activity) {
            ((Activity) context).runOnUiThread(r);
        } else {
            r.run();
        }
    } catch (Exception e) {
    }

}

From source file:com.gsr.myschool.server.reporting.bilan.ConvocationReportController.java

@RequestMapping(method = RequestMethod.GET, value = "/convocationReport", produces = "application/pdf")
@ResponseStatus(HttpStatus.OK)// w w w .  j  a va  2s  . c om
public void generateExcel(@RequestParam String fileName, HttpServletRequest request,
        HttpServletResponse response) {
    try {
        final int buffersize = 1024;
        final byte[] buffer = new byte[buffersize];

        response.addHeader("Content-Disposition", "attachment; filename=convocation_report.pdf");

        File file = new File(
                request.getSession().getServletContext().getRealPath("/") + TMP_FOLDER_PATH + fileName);
        InputStream inputStream = new FileInputStream(file);
        BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());

        int available = 0;
        while ((available = inputStream.read(buffer)) >= 0) {
            outputStream.write(buffer, 0, available);
        }

        inputStream.close();

        outputStream.flush();
        outputStream.close();

        file.delete();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:jeffaschenk.tomcat.instance.generator.builders.TomcatInstanceBuilderHelper.java

/**
 * Pull specified Version of Tomcat from Internet Download Site ...
 *
 * @param GENERATION_LOGGER Logger//  w  ww . j  a  v a 2 s.  c o  m
 * @param tomcatInstance    POJO
 */
protected static boolean pullTomcatVersionFromApacheMirror(GenerationLogger GENERATION_LOGGER,
        TomcatAvailableArchives tomcatAvailableArchives, TomcatInstance tomcatInstance) {
    /**
     * First determine the Latest Release based upon our Short name.
     */
    TomcatArchive tomcatArchive = tomcatAvailableArchives
            .getAvailableArchiveByShortName(tomcatInstance.getTomcatVersion());
    if (tomcatArchive == null || tomcatArchive.getShortVersion() == null) {
        GENERATION_LOGGER.error("Unable to determine a Download Archive for Tomcat Version: "
                + tomcatInstance.getTomcatVersion() + ", Notify Engineering to Support new Version of Tomcat!");
        return false;
    }
    tomcatInstance.setTomcatArchive(tomcatArchive); // Set a Reference to archive used.
    /**
     * Now check to see if the Artifact has already been pulled?
     */
    if (validateTomcatDownloadedVersion(GENERATION_LOGGER, tomcatInstance, false)) {
        GENERATION_LOGGER.info("Using previously Downloaded Archive: " + tomcatArchive.getName() + ".zip");
        return true;
    }
    /**
     * Proceed to Pull Archive ...
     */
    GENERATION_LOGGER.info("Pulling Tomcat Version from Apache Mirror ...");

    URL url = null;
    URLConnection con = null;
    int i;
    try {
        /**
         * Construct the Apache Mirror URL to Pull Tomcat Instance.
         * Assume a V8 version ...
         */
        String tcHeadVersion;
        if (tomcatInstance.getTomcatVersion().startsWith("v8")) {
            tcHeadVersion = DefaultDefinitions.APACHE_TOMCAT_8_MIRROR_HEAD;
        } else if (tomcatInstance.getTomcatVersion().startsWith("v9")) {
            tcHeadVersion = DefaultDefinitions.APACHE_TOMCAT_9_MIRROR_HEAD;
        } else {
            GENERATION_LOGGER.error("Unable to determine a Download URL for Tomcat Version: "
                    + tomcatInstance.getTomcatVersion()
                    + ", Notify Engineering to Support new Version of Tomcat!");
            return false;
        }
        /**
         * Now construct the URL to use to Pull over Internet.
         */
        url = new URL(tomcatAvailableArchives.getApacheMirrorHeadUrl() + "/" + tcHeadVersion + "/v"
                + tomcatArchive.getShortVersion() + "/bin/" + tomcatArchive.getName() + ".zip");
        GENERATION_LOGGER.info("Using URL for Downloading Artifact: " + url.toString());

        con = url.openConnection();
        BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(tomcatInstance.getDestinationFolder().getAbsolutePath() + File.separator
                        + tomcatArchive.getName() + ".zip"));
        while ((i = bis.read()) != -1) {
            bos.write(i);
        }
        bos.flush();
        bis.close();
        GENERATION_LOGGER.info("Successfully Pulled Tomcat Version from Apache Mirror ...");
        return true;
    } catch (MalformedInputException malformedInputException) {
        malformedInputException.printStackTrace();
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }
    /**
     * Indicate a Failure has Occurred
     */
    return false;
}

From source file:org.apache.synapse.samples.framework.clients.MTOMSwASampleClient.java

public SampleClientResult sendUsingMTOM(String fileName, String targetEPR) {
    clientResult = new SampleClientResult();
    try {//from   w  ww . ja va2s  .c o  m
        OMFactory factory = OMAbstractFactory.getOMFactory();
        OMNamespace ns = factory.createOMNamespace("http://services.samples", "m0");
        payload = factory.createOMElement("uploadFileUsingMTOM", ns);
        OMElement request = factory.createOMElement("request", ns);
        OMElement image = factory.createOMElement("image", ns);

        log.info("Sending file : " + fileName + " as MTOM");
        FileDataSource fileDataSource = new FileDataSource(new File(fileName));
        DataHandler dataHandler = new DataHandler(fileDataSource);
        OMText textData = factory.createOMText(dataHandler, true);
        image.addChild(textData);
        request.addChild(image);
        payload.addChild(request);

        ConfigurationContext configContext = ConfigurationContextFactory
                .createConfigurationContextFromFileSystem(configuration.getClientRepo(),
                        configuration.getAxis2Xml());

        serviceClient = new ServiceClient(configContext, null);

        Options options = new Options();
        options.setTo(new EndpointReference(targetEPR));
        options.setAction("urn:uploadFileUsingMTOM");
        options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);

        serviceClient.setOptions(options);
        OMElement response = serviceClient.sendReceive(payload);

        OMText binaryNode = (OMText) response
                .getFirstChildWithName(new QName("http://services.samples", "response"))
                .getFirstChildWithName(new QName("http://services.samples", "image")).getFirstOMChild();
        dataHandler = (DataHandler) binaryNode.getDataHandler();
        InputStream is = dataHandler.getInputStream();
        log.info("temp.dir: " + System.getProperty("java.io.tmpdir"));
        File tempFile = File.createTempFile("mtom-", ".gif");
        FileOutputStream fos = new FileOutputStream(tempFile);
        BufferedOutputStream dest = new BufferedOutputStream(fos, 2048);

        byte data[] = new byte[2048];
        int count;
        while ((count = is.read(data, 0, 2048)) != -1) {
            dest.write(data, 0, count);
        }

        dest.flush();
        dest.close();
        log.info("Saved response to file : " + tempFile.getAbsolutePath());
        clientResult.incrementResponseCount();
    } catch (Exception e) {
        log.error("Error invoking service", e);
        clientResult.setException(e);
    }

    return clientResult;

}