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:fr.eoidb.util.ImageDownloader.java

private void flushSingleCacheFileToDisk(Bitmap bitmap, String cacheIconName, Context context)
        throws IOException {
    File cacheIconFile = new File(context.getCacheDir(), cacheIconName);
    if (!cacheIconFile.exists()) {
        if (BuildConfig.DEBUG)
            Log.v(LOG_TAG, "Flushing bitmap " + cacheIconName + " to disk...");
        cacheIconFile.createNewFile();//from www.  j av  a  2  s . c  o m

        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(cacheIconFile));
        bitmap.compress(CompressFormat.PNG, 100, bos);
        bos.flush();
        bos.close();
    }
}

From source file:com.commonsware.android.documents.consumer.DurablizerService.java

private Uri makeLocalCopy(Uri document) {
    DocumentFile docFile = buildDocFileForUri(document);
    Uri result = null;/*from   w  w  w . ja v  a  2s.  c  om*/

    if (docFile.getName() != null) {
        File f = new File(getFilesDir(), docFile.getName());

        try {
            FileOutputStream fos = new FileOutputStream(f);
            BufferedOutputStream out = new BufferedOutputStream(fos);
            InputStream in = getContentResolver().openInputStream(document);

            try {
                byte[] buffer = new byte[8192];
                int len = 0;

                while ((len = in.read(buffer)) >= 0) {
                    out.write(buffer, 0, len);
                }

                out.flush();
                result = Uri.fromFile(f);
            } finally {
                fos.getFD().sync();
                out.close();
                in.close();
            }
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), "Exception copying content to file", e);
        }
    }

    return (result);
}

From source file:com.honnix.yaacs.adapter.http.ui.ACHttpClientCli.java

private void save(String filePath, InputStream is) throws IOException {
    File file = new File(filePath);
    File directory = new File(file.getParent());

    if (!directory.exists()) {
        directory.mkdirs();/*  w w w. j a v a  2 s  .  co  m*/
    }

    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
    BufferedInputStream bis = new BufferedInputStream(is);
    byte[] buffer = new byte[255];
    int length = -1;

    while ((length = bis.read(buffer)) != -1) {
        bos.write(buffer, 0, length);
    }

    bos.flush();
    StreamUtil.closeStream(bos);
    StreamUtil.closeStream(bis);
}

From source file:edu.cmu.android.restaurant.MapFragment.java

public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == TAKE_PICTURE) {
        if (resultCode == Activity.RESULT_OK) {
            Bitmap bm = (Bitmap) data.getExtras().get("data");
            SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmssZ");
            String dateStr = sdf.format(new Date());
            File myCaptureFile = new File(
                    Environment.getExternalStorageDirectory().getPath() + "/" + dateStr + ".jpg");
            try {

                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                bos.flush();
                bos.close();/* www  .j  a va 2  s .  c  o m*/

            } catch (FileNotFoundException e) {
                Log.e(TAG, e.getMessage(), e);

            } catch (IOException e) {
                Log.e(TAG, e.getMessage(), e);
            }
        }
    }
}

From source file:it.readbeyond.minstrel.librarian.FormatHandlerAbstractZIP.java

protected void extractCover(File f, Format format, String publicationID) {
    String destinationName = publicationID + "." + format.getName() + ".png";
    String entryName = format.getMetadatum("internalPathCover");

    if ((entryName == null) || (entryName.equals(""))) {
        format.addMetadatum("relativePathThumbnail", "");
        return;//from  ww  w  . ja v a 2 s.  c  om
    }

    try {
        ZipFile zipFile = new ZipFile(f, ZipFile.OPEN_READ);
        ZipEntry entry = zipFile.getEntry(entryName);
        File destFile = new File(this.thumbnailDirectoryPath, "orig-" + destinationName);
        String destinationPath = destFile.getAbsolutePath();

        BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry));
        int numberOfBytesRead;
        byte data[] = new byte[BUFFER_SIZE];

        FileOutputStream fos = new FileOutputStream(destFile);
        BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE);

        while ((numberOfBytesRead = is.read(data, 0, BUFFER_SIZE)) > -1) {
            dest.write(data, 0, numberOfBytesRead);
        }
        dest.flush();
        dest.close();
        is.close();
        fos.close();

        // create thumbnail
        FileInputStream fis = new FileInputStream(destinationPath);
        Bitmap imageBitmap = BitmapFactory.decodeStream(fis);
        imageBitmap = Bitmap.createScaledBitmap(imageBitmap, this.thumbnailWidth, this.thumbnailHeight, false);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] imageData = baos.toByteArray();

        // write thumbnail to file 
        File destFile2 = new File(this.thumbnailDirectoryPath, destinationName);
        String destinationPath2 = destFile2.getAbsolutePath();
        FileOutputStream fos2 = new FileOutputStream(destFile2);
        fos2.write(imageData, 0, imageData.length);
        fos2.flush();
        fos2.close();
        baos.close();

        // close ZIP
        zipFile.close();

        // delete original cover
        destFile.delete();

        // set relativePathThumbnail
        format.addMetadatum("relativePathThumbnail", destinationName);

    } catch (Exception e) {
        // nop 
    }
}

From source file:SimpleFTP.java

/**
 * Sends a file to be stored on the FTP server. Returns true if the file
 * transfer was successful. The file is sent in passive mode to avoid NAT or
 * firewall problems at the client end.//from  w w w.j ava2 s .  co  m
 */
public synchronized boolean stor(InputStream inputStream, String filename) throws IOException {

    BufferedInputStream input = new BufferedInputStream(inputStream);

    sendLine("PASV");
    String response = readLine();
    if (!response.startsWith("227 ")) {
        throw new IOException("SimpleFTP could not request passive mode: " + response);
    }

    String ip = null;
    int port = -1;
    int opening = response.indexOf('(');
    int closing = response.indexOf(')', opening + 1);
    if (closing > 0) {
        String dataLink = response.substring(opening + 1, closing);
        StringTokenizer tokenizer = new StringTokenizer(dataLink, ",");
        try {
            ip = tokenizer.nextToken() + "." + tokenizer.nextToken() + "." + tokenizer.nextToken() + "."
                    + tokenizer.nextToken();
            port = Integer.parseInt(tokenizer.nextToken()) * 256 + Integer.parseInt(tokenizer.nextToken());
        } catch (Exception e) {
            throw new IOException("SimpleFTP received bad data link information: " + response);
        }
    }

    sendLine("STOR " + filename);

    Socket dataSocket = new Socket(ip, port);

    response = readLine();
    if (!response.startsWith("125 ")) {
        //if (!response.startsWith("150 ")) {
        throw new IOException("SimpleFTP was not allowed to send the file: " + response);
    }

    BufferedOutputStream output = new BufferedOutputStream(dataSocket.getOutputStream());
    byte[] buffer = new byte[4096];
    int bytesRead = 0;
    while ((bytesRead = input.read(buffer)) != -1) {
        output.write(buffer, 0, bytesRead);
    }
    output.flush();
    output.close();
    input.close();

    response = readLine();
    return response.startsWith("226 ");
}

From source file:fr.enseirb.odroidx.videomanager.Uploader.java

public void doUpload(Uri myFile) {
    createNotification();/*from   w  w w  . j  a va2s .co m*/
    File f = new File(myFile.getPath());
    SendName(f.getName().replace(' ', '-'));
    Log.e(getClass().getSimpleName(), "test: " + f.exists());
    if (f.exists()) {
        Socket s;
        try {
            Log.e(getClass().getSimpleName(), "test: " + server_ip);
            s = new Socket(InetAddress.getByName(server_ip), 5088);// Bug
            // using
            // variable
            // port
            OutputStream fluxsortie = s.getOutputStream();
            int nb_parts = (int) (f.length() / PART_SIZE);

            InputStream in = new BufferedInputStream(new FileInputStream(f));
            ByteArrayOutputStream byte_array = new ByteArrayOutputStream();
            BufferedOutputStream buffer = new BufferedOutputStream(byte_array);

            byte[] to_write = new byte[PART_SIZE];
            for (int i = 0; i < nb_parts; i++) {
                in.read(to_write, 0, PART_SIZE);
                buffer.write(to_write);
                buffer.flush();
                fluxsortie.write(byte_array.toByteArray());
                byte_array.reset();
                if ((i % 250) == 0) {
                    mBuilder.setProgress(nb_parts, i, false);
                    mNotifyManager.notify(NOTIFY_ID, mBuilder.getNotification());
                }
            }
            int remaining = (int) (f.length() - nb_parts * PART_SIZE);
            in.read(to_write, 0, remaining);
            buffer.write(to_write);
            buffer.flush();
            fluxsortie.write(byte_array.toByteArray());
            byte_array.reset();
            buffer.close();
            fluxsortie.close();
            in.close();
            s.close();
        } catch (ConnectException e) {
            if (STATUS != HTTP_SERVER)
                STATUS = CONNECTION_ERROR;
            e.printStackTrace();
        } catch (UnknownHostException e) {
            if (STATUS != HTTP_SERVER)
                STATUS = UNKNOWN;
            Log.i(getClass().getSimpleName(), "Unknown host");
            e.printStackTrace();
        } catch (IOException e) {
            if (STATUS != HTTP_SERVER)
                STATUS = CONNECTION_ERROR;
            e.printStackTrace();
        }
    }
}

From source file:edu.cloud.iot.reception.ocr.ScanLicense.java

public void saveImage(String pPath, String pDir, Bitmap img) {
    try {/*  w  ww.  jav  a2s. c  o  m*/
        FileOutputStream fos = new FileOutputStream(pPath + pDir);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        // Compress Bitmap Image
        image.compress(Bitmap.CompressFormat.JPEG, 50, bos);
        bos.flush();
        bos.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        Log.v("EDebug::FaceRecognitionActivity", ex.getMessage() + "");
    }
}

From source file:com.feilong.tools.net.filetransfer.FTPUtil.java

@Override
protected boolean _downRemoteSingleFile(String remoteSingleFile, String filePath) throws Exception {
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(filePath));
    boolean success = ftpClient.retrieveFile(remoteSingleFile, bufferedOutputStream);

    bufferedOutputStream.flush();
    bufferedOutputStream.close();//w  w w . j a va  2  s.co m
    return success;
}

From source file:ebay.dts.client.FileTransferActions.java

public void downloadFile2(String fileName, String jobId, String fileReferenceId) throws EbayConnectorException {

    String callName = "downloadFile";

    try {//from www  .  j av a 2 s . c  o  m

        FileTransferServicePort port = call.setFTSMessageContext(callName);
        com.ebay.marketplace.services.DownloadFileRequest request = new com.ebay.marketplace.services.DownloadFileRequest();
        request.setFileReferenceId(fileReferenceId);
        request.setTaskReferenceId(jobId);
        DownloadFileResponse response = port.downloadFile(request);
        if (response.getAck().equals(AckValue.SUCCESS)) {
            logger.debug(AckValue.SUCCESS.toString());
        } else {
            logger.error(response.getErrorMessage().getError().get(0).getMessage());
            throw new EbayConnectorException(response.getErrorMessage().getError().get(0).getMessage());
        }

        FileAttachment attachment = response.getFileAttachment();
        DataHandler dh = attachment.getData();

        try {
            InputStream in = dh.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(new GZIPInputStream(in));
            FileOutputStream fo = new FileOutputStream(new File(fileName)); // "C:/myDownLoadFile.gz"
            BufferedOutputStream bos = new BufferedOutputStream(fo);
            int bytes_read = 0;
            byte[] dataBuf = new byte[4096];
            while ((bytes_read = bis.read(dataBuf)) != -1) {
                bos.write(dataBuf, 0, bytes_read);
            }
            bis.close();
            bos.flush();
            bos.close();
            logger.info("File attachment has been saved successfully to " + fileName);

        } catch (IOException e) {
            logger.error("Exception caught while trying to save the attachement");
            throw new EbayConnectorException("Exception caught while trying to save the attachement", e);
        }

    } catch (Exception e) {
        throw new EbayConnectorException("Exception caught while trying to save the attachement", e);
    }

}