Example usage for java.io FileOutputStream flush

List of usage examples for java.io FileOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:Main.java

public static void saveWeiboBitmap(Bitmap bitmap, String filename) {
    String status = Environment.getExternalStorageState();
    if (bitmap == null || !status.equals(Environment.MEDIA_MOUNTED)) {
        return;/*from   ww  w.  ja  va 2 s. c  o  m*/
    }
    File f = new File(filename);
    FileOutputStream fOut = null;
    boolean error = false;
    try {
        f.createNewFile();
    } catch (IOException e1) {
        e1.printStackTrace();
        error = true;
    }

    try {
        fOut = new FileOutputStream(f);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        error = true;
    }

    try {
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
    } catch (Exception e) {
        e.printStackTrace();
        error = true;
    }

    try {
        fOut.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        fOut.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:Main.java

public static File saveBitmapToExternal(Bitmap bitmap, String targetFileDirPath) {
    if (bitmap == null || bitmap.isRecycled()) {
        return null;
    }/*from  ww w .jav  a 2  s.co m*/

    File targetFileDir = new File(targetFileDirPath);
    if (!targetFileDir.exists() && !targetFileDir.mkdirs()) {
        return null;
    }

    File targetFile = new File(targetFileDir, UUID.randomUUID().toString());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(targetFile);
        baos.writeTo(fos);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            baos.flush();
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (fos != null) {
                fos.flush();
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return targetFile;
}

From source file:org.solrsystem.Main.java

public static boolean doGetToFile(String url, String localFilePath, DownloadStatusListener listener)
        throws HttpException, IOException {
    final HttpGet request = new HttpGet(url);
    final HttpResponse resp;
    try {/*from ww w.ja v a 2  s  . c  o m*/
        DefaultHttpClient httpClient = new DefaultHttpClient();

        resp = httpClient.execute(request);
        long totalnum = resp.getEntity().getContentLength();
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            FileOutputStream out = new FileOutputStream(localFilePath);

            InputStream inputStream = resp.getEntity().getContent();

            long bytesRead = 0;
            int bufferSize = listener.progressInterval();
            byte b[] = new byte[bufferSize];

            int cnt;
            System.out.println("reading " + bufferSize);
            while ((cnt = inputStream.read(b)) != -1) {
                out.write(b, 0, cnt);
                bytesRead += cnt;
                listener.onProgress(bytesRead, totalnum);
            }
            out.flush();
            out.close();

            //resp.getEntity().writeTo(out);

            out.close();
            return true;
        } else {
            System.out.println("Download Failed:" + resp.getStatusLine());
            return false;
        }
    } catch (final IOException e) {
        e.printStackTrace();
        throw new HttpException("IOException " + e.toString());
    }
}

From source file:com.ephesoft.dcma.util.PDFUtil.java

/**
 * The <code>closePassedStream</code> method closes the stream passed.
 * // ww  w.  j  a v  a  2 s  . c om
 * @param reader {@link PdfReader}
 * @param document {@link Document}
 * @param contentByte {@link PdfContentByte}
 * @param writer {@link PdfWriter}
 * @param fileInputStream {@link FileInputStream}
 * @param fileOutputStream {@link FileOutputStream}
 * @throws IOException {@link} if unable to close input or output stream
 */
private static void closePassedStream(final PdfReader reader, final Document document,
        final PdfContentByte contentByte, final PdfWriter writer, final FileInputStream fileInputStream,
        final FileOutputStream fileOutputStream) throws IOException {
    if (null != reader) {
        reader.close();
    }
    if (null != document) {
        document.close();
    }
    if (null != contentByte) {
        contentByte.closePath();
    }
    if (null != writer) {
        writer.close();
    }
    if (null != fileInputStream) {
        fileInputStream.close();
    }

    if (null != fileOutputStream) {
        fileOutputStream.flush();
        fileOutputStream.close();
    }
}

From source file:com.stacksync.desktop.util.FileUtil.java

public static void createWindowsLink(String link, String target) {
    // TODO Is it always working fine???
    File FileLink = new File(link);
    if (!FileLink.exists()) {
        String script = "Set sh = CreateObject(\"WScript.Shell\")" + "\nSet shortcut = sh.CreateShortcut(\""
                + link + "\")" + "\nshortcut.TargetPath = \"" + target + "\"" + "\nshortcut.Save";

        File file = new File(env.getDefaultUserConfigDir() + File.separator + "temp.vbs");
        try {/*from w w  w . ja  va  2  s  .c om*/
            FileOutputStream fo = new FileOutputStream(file);
            fo.write(script.getBytes());
            fo.flush();
            fo.close();

            Runtime.getRuntime().exec("wscript.exe \"" + file.getAbsolutePath() + "\"");
        } catch (IOException ex) {
            logger.error(ex);
            RemoteLogs.getInstance().sendLog(ex);
        }
    }
}

From source file:com.oakhole.voa.utils.HttpClientUtils.java

/**
 * ?get?//from  www.j ava2 s  .c  o  m
 *
 * @param uri
 * @param file
 * @return
 */
public static String getFile(String uri, File file) {
    HttpEntity entity = get(uri);
    if (entity != null) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            InputStream inputStream = entity.getContent();
            //
            byte[] bytes = new byte[1024];
            int length = 0;
            while (((length = inputStream.read(bytes)) != -1)) {
                fileOutputStream.write(bytes, 0, length);
            }
            //
            fileOutputStream.flush();
            fileOutputStream.close();
            inputStream.close();
        } catch (IOException e) {
            logger.error(":{}", e.getMessage());
        }
    }
    return "";
}

From source file:com.frostwire.gui.updates.InstallerUpdater.java

public final static void downloadTorrentFile(String torrentURL, File saveLocation)
        throws IOException, URISyntaxException {
    byte[] contents = new HttpFetcher(new URI(torrentURL)).fetch();

    // save the torrent locally if you have to
    if (saveLocation != null && contents != null && contents.length > 0) {

        if (saveLocation.exists()) {
            saveLocation.delete();//from   w  ww  . j  av  a 2 s  .  c  o  m
        }

        //Create all the route necessary to save the .torrent file if it does not exit.
        saveLocation.getParentFile().mkdirs();
        saveLocation.createNewFile();
        saveLocation.setWritable(true);

        FileOutputStream fos = new FileOutputStream(saveLocation, false);
        fos.write(contents);
        fos.flush();
        fos.close();
    }
}

From source file:Main.java

/**
 * Write DOM to a file/*from w ww.  j a  va  2 s .  c o m*/
 *
 * @param doc
 *            DOM document
 * @param filename
 *            target file name
 * @param encoding
 *            specified encoding
 * @param omitXmlDeclaration
 *            flag to indicate if xml declaration statement is included
 * @throws Exception
 */
public static void writeXmlFile(Document doc, String filename, String encoding, String omitXmlDeclaration)
        throws Exception {

    // Prepare the DOM document for writing
    Source source = new DOMSource(doc);

    // Prepare the output file
    FileOutputStream outputStream = new FileOutputStream(new File(filename));
    Result result = new StreamResult(outputStream);

    // Write the DOM document to the file
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXmlDeclaration);

    transformer.transform(source, result);

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

From source file:com.frostwire.android.gui.util.UIUtils.java

/**
 * Takes a screenshot of the given view/*from  w  w  w.  ja  v  a 2  s  . com*/
 * @return File with jpeg of the screenshot taken. null if there was a problem.
 */
public static File takeScreenshot(View view) {
    view.setDrawingCacheEnabled(true);
    try {
        Thread.sleep(300);
    } catch (Throwable t) {
    }
    Bitmap drawingCache = null;
    try {
        drawingCache = view.getDrawingCache();
    } catch (Throwable ignored) {
    }
    Bitmap screenshotBitmap = null;
    if (drawingCache != null) {
        try {
            screenshotBitmap = Bitmap.createBitmap(drawingCache);
        } catch (Throwable ignored) {
        }
    }
    view.setDrawingCacheEnabled(false);
    if (screenshotBitmap == null) {
        return null;
    }
    File screenshotFile = new File(Environment.getExternalStorageDirectory().toString(),
            "fwPlayerScreenshot.tmp.jpg");
    if (screenshotFile.exists()) {
        screenshotFile.delete();
        try {
            screenshotFile.createNewFile();
        } catch (IOException ignore) {
        }
    }
    try {
        FileOutputStream fos = new FileOutputStream(screenshotFile);
        screenshotBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
    } catch (Throwable t) {
        screenshotFile.delete();
        screenshotFile = null;
    }
    return screenshotFile;
}

From source file:de.mpg.imeji.logic.storage.util.ImageUtils.java

/**
 * Transform a image {@link File} to a jpeg file
 * // w  w  w .ja  v  a 2 s.  c  o  m
 * @param f - the {@link File} where the image is
 * @param dec - The {@link ImageDecoder} needed to decode the passed image
 * @return the image as {@link Byte} array
 */
private static byte[] image2Jpeg(File f, ImageDecoder dec) {
    try {
        RenderedImage ri = dec.decodeAsRenderedImage(0);
        File jpgFile = File.createTempFile("imeji_upload", "jpg.tmp");
        FileOutputStream fos = new FileOutputStream(jpgFile);
        JPEGEncodeParam jParam = new JPEGEncodeParam();
        jParam.setQuality(1.0f);
        ImageEncoder imageEncoder = ImageCodec.createImageEncoder("JPEG", fos, jParam);
        imageEncoder.encode(ri);
        fos.flush();
        return FileUtils.readFileToByteArray(jpgFile);
    } catch (Exception e) {
        throw new RuntimeException("Error transforming image file to jpeg", e);
    }
}