Example usage for java.io OutputStream flush

List of usage examples for java.io OutputStream flush

Introduction

In this page you can find the example usage for java.io OutputStream 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:jeevlet.representation.BlobRepresentation.java

private static void copy(InputStream in, OutputStream output) throws IOException {
    BufferedInputStream input = new BufferedInputStream(in);
    try {//ww  w. ja  v a2 s . com
        byte buffer[] = new byte[BUF_SIZE];
        int nRead;
        do {
            nRead = input.read(buffer, 0, BUF_SIZE);
            output.write(buffer, 0, nRead);

        } while (nRead == BUF_SIZE);
        input.close();
    } catch (IOException e) {
        input.close();
        throw e;
    }
    output.flush();
}

From source file:Main.java

private static File unzip(Context context, InputStream in) throws IOException {
    File tmpDb = null;/* w ww  .ja v a 2  s.co  m*/
    int dbFiles = 0;
    try {
        tmpDb = File.createTempFile("import", ".db");

        ZipInputStream zin = new ZipInputStream(in);
        ZipEntry sourceEntry;
        while (true) {

            sourceEntry = zin.getNextEntry();

            if (sourceEntry == null) {
                break;
            }

            if (sourceEntry.isDirectory()) {
                zin.closeEntry();
                continue;
            }

            FileOutputStream fOut;
            if (sourceEntry.getName().endsWith(".db")) {
                // Write database to tmp file
                fOut = new FileOutputStream(tmpDb);
                dbFiles++;
            } else {
                // Write all other files(images) to files dir in apps data
                int start = sourceEntry.getName().lastIndexOf("/") + 1;
                String name = sourceEntry.getName().substring(start);
                fOut = context.openFileOutput(name, Context.MODE_PRIVATE);
            }

            final OutputStream targetStream = fOut;
            try {
                int read;
                while (true) {
                    byte[] buffer = new byte[1024];
                    read = zin.read(buffer);
                    if (read == -1) {
                        break;
                    }
                    targetStream.write(buffer, 0, read);
                }
                targetStream.flush();
            } finally {
                safeCloseClosable(targetStream);
            }
            zin.closeEntry();
        }
    } finally {
        safeCloseClosable(in);
    }
    if (dbFiles != 1) {
        throw new IllegalStateException("Input file is not a valid backup");
    }
    return tmpDb;
}

From source file:com.jsonstore.util.JSONStoreUtil.java

/**
 * copy input stream to output stream/* w w  w  .  jav a  2  s . c  o m*/
 * @param in The {@link InputStream} object to be copied from.
 * @param out The {@link OutputStream} object to write to.
 * @throws IOException in case copy fails.
 */
public static void copyFile(InputStream in, OutputStream out) throws IOException {
    // 8k is the suggest buffer size in android, do not change this
    byte[] buffer = new byte[ANDROID_BUFFER_8K];
    int read;
    while ((read = in.read(buffer)) != -1) {
        out.write(buffer, 0, read);
    }
    out.flush();
}

From source file:cn.bluemobi.util.file.ImgHelper.java

/**
 * base64?//  www. ja v a 2 s  .  c  o  m
 * @param base64Str
 * @param imgPath
 * @return
 */
public static boolean generateImage(String base64Str, File file) {// Base64??
    if (base64Str == null) // ??
        return false;
    BASE64Decoder decoder = new BASE64Decoder();
    try {
        // Base64?
        byte[] b = decoder.decodeBuffer(base64Str);
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {// ?
                b[i] += 256;
            }
        }
        File parent = file.getParentFile();
        if (parent != null && !parent.exists()) {
            parent.mkdirs();
        }

        // ?jpeg
        OutputStream out = new FileOutputStream(file);
        out.write(b);
        out.flush();
        out.close();
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:com.photon.phresco.service.util.DependencyUtils.java

/**
 * Extracts the given compressed file (of type tar, targz, and zip) into given location.
 * See also/* ww  w .  j  a v  a 2 s.  c  om*/
 * {@link ArchiveType} and {@link ArchiveUtil}
 * @param contentURL
 * @param path
 * @throws PhrescoException
 */
public static void extractFiles(String contentURL, String folderName, File path, String customerId)
        throws PhrescoException {
    if (isDebugEnabled) {
        LOGGER.debug("DependencyUtils.extractFiles:Entry");
        LOGGER.info(ServiceConstants.DEPENDENCY_UTIL_EXTRACT_FILES, "contentURL=\"" + contentURL + "\"",
                "folderName=\"" + folderName + "\"", ServiceConstants.PATH_EQUALS_SLASH + path.getName() + "\"",
                ServiceConstants.CUSTOMER_ID_EQUALS_SLASH + customerId + "\"");
    }
    assert !StringUtils.isEmpty(contentURL);

    PhrescoServerFactory.initialize();
    String extension = getExtension(contentURL);
    File archive = new File(Utility.getPhrescoTemp(), UUID.randomUUID().toString() + extension);
    FileOutputStream fos = null;
    OutputStream out = null;
    try {
        InputStream inputStream = PhrescoServerFactory.getRepositoryManager().getArtifactAsStream(contentURL,
                customerId);
        fos = new FileOutputStream(archive);
        out = new BufferedOutputStream(fos);

        IOUtils.copy(inputStream, out);

        out.flush();
        out.close();
        fos.close();
        ArchiveType archiveType = getArchiveType(extension);
        if (isDebugEnabled) {
            LOGGER.debug("extractFiles() path=" + path.getPath());
        }
        ArchiveUtil.extractArchive(archive.toString(), path.getAbsolutePath(), folderName, archiveType);
        archive.delete();
        if (isDebugEnabled) {
            LOGGER.debug("DependencyUtils.extractFiles:Exit");
        }
    } catch (FileNotFoundException e) {
        LOGGER.error(ServiceConstants.DEPENDENCY_UTIL_EXTRACT_FILES, ServiceConstants.STATUS_FAILURE,
                "message=\"" + e.getLocalizedMessage() + "\"");
        return;
    }

    catch (IOException e) {
        LOGGER.error(ServiceConstants.DEPENDENCY_UTIL_EXTRACT_FILES, ServiceConstants.STATUS_FAILURE,
                "message=\"" + e.getLocalizedMessage() + "\"");
        throw new PhrescoException(e);
    } catch (PhrescoException pe) {
        LOGGER.error(ServiceConstants.DEPENDENCY_UTIL_EXTRACT_FILES, ServiceConstants.STATUS_FAILURE,
                "message=\"" + pe.getLocalizedMessage() + "\"");
        if (pe.getCause() instanceof FileNotFoundException) {
            return;
        }
        throw pe;
    } finally {
        Utility.closeStream(fos);
        Utility.closeStream(out);
    }
}

From source file:fr.aliasource.webmail.server.calendar.CalendarProxyImpl.java

/**
 * Fast stream transfer method//from www .jav  a2 s  . co m
 * 
 * @param in
 * @param out
 * @throws IOException
 */
public static void transfer(InputStream in, OutputStream out, boolean closeIn) throws IOException {
    final byte[] buffer = new byte[4096];

    try {
        while (true) {
            int amountRead = in.read(buffer);
            if (amountRead == -1) {
                break;
            }
            out.write(buffer, 0, amountRead);
        }
    } finally {
        if (closeIn) {
            in.close();
        }
        out.flush();
        out.close();
    }
}

From source file:Main.java

/**
 * Save jpeg image with background color
 * @param strFileName Save file path/*  w  w  w.ja v  a2 s. co m*/
 * @param bitmap Input bitmap
 * @param nQuality Jpeg quality for saving
 * @param nBackgroundColor background color
 * @return whether success or not
 */
public static boolean saveBitmapJPEGWithBackgroundColor(String strFileName, Bitmap bitmap, int nQuality,
        int nBackgroundColor) {
    boolean bSuccess1 = false;
    boolean bSuccess2 = false;
    boolean bSuccess3;
    File saveFile = new File(strFileName);

    if (saveFile.exists()) {
        if (!saveFile.delete())
            return false;
    }

    int nA = (nBackgroundColor >> 24) & 0xff;

    // If Background color alpha is 0, Background color substitutes as white
    if (nA == 0)
        nBackgroundColor = 0xFFFFFFFF;

    Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(newBitmap);
    canvas.drawColor(nBackgroundColor);
    canvas.drawBitmap(bitmap, rect, rect, new Paint());

    // Quality limitation min/max
    if (nQuality < 10)
        nQuality = 10;
    else if (nQuality > 100)
        nQuality = 100;

    OutputStream out = null;

    try {
        bSuccess1 = saveFile.createNewFile();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    try {
        out = new FileOutputStream(saveFile);
        bSuccess2 = newBitmap.compress(CompressFormat.JPEG, nQuality, out);
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        if (out != null) {
            out.flush();
            out.close();
            bSuccess3 = true;
        } else
            bSuccess3 = false;

    } catch (IOException e) {
        e.printStackTrace();
        bSuccess3 = false;
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return (bSuccess1 && bSuccess2 && bSuccess3);
}

From source file:net.menthor.editor.v2.util.Util.java

/** Extract a file from menthor's library class path */
public static File extractLib(String fileNameWithExtension, String destFolderPath) throws IOException {
    if (destFolderPath.lastIndexOf("/") < destFolderPath.lastIndexOf(".")) {
        int lastBar = destFolderPath.lastIndexOf("/");
        destFolderPath = destFolderPath.substring(0, lastBar + 1);
    }/*from   w ww . ja  va 2s .c o  m*/
    destFolderPath += fileNameWithExtension;
    String path = URLDecoder.decode(destFolderPath, "UTF-8");
    File File = new File(path);
    if (File.exists())
        return File;
    InputStream is = Util.class.getClassLoader().getResourceAsStream(fileNameWithExtension);
    if (is == null)
        is = new FileInputStream(fileNameWithExtension);
    OutputStream out = new FileOutputStream(File);
    // copy data flow -> MB x MB
    byte[] src = new byte[1024];
    int read = 0;
    while ((read = is.read(src)) != -1) {
        out.write(src, 0, read);
    }
    is.close();
    out.flush();
    out.close();
    return File;
}

From source file:JarUtils.java

public static void unjar(InputStream in, File dest) throws IOException {
    if (!dest.exists()) {
        dest.mkdirs();//from   ww w.java 2 s  .c  om
    }
    if (!dest.isDirectory()) {
        throw new IOException("Destination must be a directory.");
    }
    JarInputStream jin = new JarInputStream(in);
    byte[] buffer = new byte[1024];

    ZipEntry entry = jin.getNextEntry();
    while (entry != null) {
        String fileName = entry.getName();
        if (fileName.charAt(fileName.length() - 1) == '/') {
            fileName = fileName.substring(0, fileName.length() - 1);
        }
        if (fileName.charAt(0) == '/') {
            fileName = fileName.substring(1);
        }
        if (File.separatorChar != '/') {
            fileName = fileName.replace('/', File.separatorChar);
        }
        File file = new File(dest, fileName);
        if (entry.isDirectory()) {
            // make sure the directory exists
            file.mkdirs();
            jin.closeEntry();
        } else {
            // make sure the directory exists
            File parent = file.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }

            // dump the file
            OutputStream out = new FileOutputStream(file);
            int len = 0;
            while ((len = jin.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            out.close();
            jin.closeEntry();
            file.setLastModified(entry.getTime());
        }
        entry = jin.getNextEntry();
    }
    /* Explicity write out the META-INF/MANIFEST.MF so that any headers such
    as the Class-Path are see for the unpackaged jar
    */
    Manifest mf = jin.getManifest();
    if (mf != null) {
        File file = new File(dest, "META-INF/MANIFEST.MF");
        File parent = file.getParentFile();
        if (parent.exists() == false) {
            parent.mkdirs();
        }
        OutputStream out = new FileOutputStream(file);
        mf.write(out);
        out.flush();
        out.close();
    }
    jin.close();
}

From source file:Main.java

static public void CopyAsset(Context ctx, File path, String filename) throws IOException {
    AssetManager assetManager = ctx.getAssets();
    InputStream in = null;/*from w  ww. j av a  2s .c o  m*/
    OutputStream out = null;

    // Copy files from asset folder to application folder
    try {
        in = assetManager.open(filename);
        out = new FileOutputStream(path.toString() + "/" + filename);
        copyFile(in, out);
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
        throw e;
    } finally {
        // Reclaim resources
        if (in != null) {
            in.close();
            in = null;
        }
        if (out != null) {
            out.flush();
            out.close();
            out = null;
        }
    }
}