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:com.waku.mmdataextract.ComprehensiveSearch.java

public static void saveImage(String imgSrc, String toFileName) {
    String toFile = "output/images/" + toFileName;
    if (new File(toFile).exists()) {
        logger.info("File already saved ->" + toFile);
        return;/*from w w w.  j  a  v  a 2s.  c  om*/
    }
    URL u = null;
    URLConnection uc = null;
    InputStream raw = null;
    InputStream in = null;
    FileOutputStream out = null;
    try {
        int endIndex = imgSrc.lastIndexOf("/") + 1;
        String encodeFileName = URLEncoder.encode(imgSrc.substring(endIndex), "UTF-8").replaceAll("[+]", "%20");
        u = new URL("http://shouji.gd.chinamobile.com" + imgSrc.substring(0, endIndex) + encodeFileName);
        uc = u.openConnection();
        String contentType = uc.getContentType();
        int contentLength = uc.getContentLength();
        if (contentType.startsWith("text/") || contentLength == -1) {
            logger.error("This is not a binary file. -> " + imgSrc);
        }
        raw = uc.getInputStream();
        in = new BufferedInputStream(raw);
        byte[] data = new byte[contentLength];
        int bytesRead = 0;
        int offset = 0;
        while (offset < contentLength) {
            bytesRead = in.read(data, offset, data.length - offset);
            if (bytesRead == -1)
                break;
            offset += bytesRead;
        }
        if (offset != contentLength) {
            logger.error("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
        }
        out = new FileOutputStream(toFile);
        out.write(data);
        out.flush();
        logger.info("Saved file " + u.toString() + " to " + toFile);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            in.close();
        } catch (Exception e) {
        }
        try {
            out.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.pieframework.runtime.utils.azure.Cspack.java

private String generateRoleProperties(Component c, File destinationDir, List<File> tmpFiles) {
    // /rolePropertiesFile:DefaultWebApp1;role.prop /rolePropertiesFile:bApp2;role.prop
    String result = "";

    for (String key : c.getChildren().keySet()) {
        if (c.getChildren().get(key) instanceof Role) {
            Role role = (Role) c.getChildren().get(key);

            if (role.getProps().get("targetFramework") != null) {
                byte[] data = role.getProps().get("targetFramework").getBytes();
                String roleId = role.getId();
                File propFile = new File(destinationDir.getPath() + File.separatorChar + roleId + ".property");
                try {
                    FileOutputStream out = new FileOutputStream(propFile);
                    tmpFiles.add(propFile);
                    out.write(data);/*w w w  .  j  av a  2  s  . c om*/
                    out.flush();
                    out.close();

                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                result += " /rolePropertiesFile:" + roleId + ";" + propFile.getPath();
            }
        }
    }

    return result;
}

From source file:ch.entwine.weblounge.tools.importer.AbstractImporterCallback.java

/**
 * Copies the contents of file <code>src</code> to <code>dest</code>.
 * //from w  ww.ja  va2  s  .  c  o m
 * @param f
 *          the file
 * @return the destination file
 */
protected void copy(File src, File dest) throws IOException {
    FileInputStream is = null;
    FileOutputStream os = null;
    try {
        is = new FileInputStream(src);
        os = new FileOutputStream(dest);
        byte buf[] = new byte[1024];
        int i;
        while ((i = is.read(buf)) != -1)
            os.write(buf, 0, i);
        os.flush();
    } catch (IOException e) {
        System.err.println("Unable to copy " + src.getPath() + " to " + dest.getPath() + ": " + e.getMessage());
        dest.delete();
    } finally {
        if (is != null)
            try {
                is.close();
            } catch (IOException e) { /* ignore */
            }
        if (os != null)
            try {
                os.close();
            } catch (IOException e) { /* ignore */
            }
    }
}

From source file:de.appplant.cordova.plugin.notification.Asset.java

/**
 * The URI for an asset.//w  w  w  .j  a va  2  s .  com
 * 
 * @param path
 *            The given asset path
 * 
 * @return The URI pointing to the given path
 */
private Uri getUriForAssetPath(String path) {
    String resPath = path.replaceFirst("file:/", "www");
    String fileName = resPath.substring(resPath.lastIndexOf('/') + 1);
    File dir = activity.getExternalCacheDir();
    if (dir == null) {
        Log.e("Asset", "Missing external cache dir");
        return Uri.EMPTY;
    }
    String storage = dir.toString() + STORAGE_FOLDER;
    File file = new File(storage, fileName);
    new File(storage).mkdir();
    try {
        AssetManager assets = activity.getAssets();
        FileOutputStream outStream = new FileOutputStream(file);
        InputStream inputStream = assets.open(resPath);
        copyFile(inputStream, outStream);
        outStream.flush();
        outStream.close();
        return Uri.fromFile(file);
    } catch (Exception e) {
        Log.e("Asset", "File not found: assets/" + resPath);
        e.printStackTrace();
    }
    return Uri.EMPTY;
}

From source file:com.phonegap.FileUtils.java

/**
 * Write contents of file./*from   w  w w . j a v a2s.co  m*/
 * 
 * @param filename         The name of the file.
 * @param data            The contents of the file.
 * @param append         T=append, F=overwrite
 * @throws FileNotFoundException, IOException
 */
public void writeAsText(String filename, String data, boolean append)
        throws FileNotFoundException, IOException {
    String FilePath = filename;
    byte[] rawData = data.getBytes();
    ByteArrayInputStream in = new ByteArrayInputStream(rawData);
    FileOutputStream out = new FileOutputStream(FilePath, append);
    byte buff[] = new byte[rawData.length];
    in.read(buff, 0, buff.length);
    out.write(buff, 0, rawData.length);
    out.flush();
    out.close();
}

From source file:info.magnolia.cms.core.version.CopyUtil.java

/**
 * import while preserving UUID, parameters supplied must be from separate workspaces
 * @param parent under which the specified node will be imported
 * @param node//from   w w w  .ja  va2 s. c o m
 * @throws RepositoryException
 * @throws IOException if failed to import or export
 * */
private void importNode(Content parent, Content node) throws RepositoryException, IOException {
    File file = File.createTempFile("mgnl", null, Path.getTempDirectory());
    FileOutputStream outStream = new FileOutputStream(file);
    node.getWorkspace().getSession().exportSystemView(node.getHandle(), outStream, false, true);
    outStream.flush();
    IOUtils.closeQuietly(outStream);
    FileInputStream inStream = new FileInputStream(file);
    parent.getWorkspace().getSession().importXML(parent.getHandle(), inStream,
            ImportUUIDBehavior.IMPORT_UUID_COLLISION_REMOVE_EXISTING);
    IOUtils.closeQuietly(inStream);
    file.delete();
    this.removeProperties(parent.getContent(node.getName()));
}

From source file:com.syrup.storage.InMemoryStorage.java

/**
 * Every time something gets saved, we write to memory.
 *//*  w  w  w . j a  v a  2 s . c om*/
private synchronized void writeMemoryToFile() {
    File f = new File(StartUpServlet.APP_DEFINITIONS);
    try {
        FileOutputStream fop = new FileOutputStream(f);
        XmlFactory g = new XmlFactory();
        Document result = g.getAsDocument(store);
        String fileOutput = XmlFactory.documentToString(result);
        byte[] fileOutputAsBytes = fileOutput.getBytes(HTTP.UTF_8);
        fop.write(fileOutputAsBytes);
        fop.flush();
        fop.close();
    } catch (Exception e) {
        logger.debug("Unable to write file", e);
    }
}

From source file:it.geosolutions.geobatch.imagemosaic.GranuleRemoverOnlineTest.java

/**
 * * deletes existing store//from   www. ja va2 s  .c  om
 * * create a brand new mosaic dir
 * * create the mosaic on GS
 * 
 */
protected ImageMosaicConfiguration createMosaicConfig() throws IOException {

    // create datastore file
    Properties datastore = new Properties();
    datastore.putAll(getPostgisParams());
    datastore.remove(PostgisNGDataStoreFactory.DBTYPE.key);
    datastore.setProperty("SPI", "org.geotools.data.postgis.PostgisNGDataStoreFactory");
    datastore.setProperty(PostgisNGDataStoreFactory.LOOSEBBOX.key, "true");
    datastore.setProperty(PostgisNGDataStoreFactory.ESTIMATED_EXTENTS.key, "false");
    File datastoreFile = new File(getTempDir(), "datastore.properties");
    LOGGER.info("Creating  " + datastoreFile);
    FileOutputStream out = new FileOutputStream(datastoreFile);
    datastore.store(out, "Datastore file created from fixtures");
    out.flush();
    out.close();
    //        datastore.store(System.out, "Datastore created from fixtures");
    //        datastore.list(System.out);

    // config
    ImageMosaicConfiguration conf = new ImageMosaicConfiguration("", "", "");
    conf.setTimeRegex("(?<=_)\\\\d{8}");
    conf.setTimeDimEnabled("true");
    conf.setTimePresentationMode("LIST");
    conf.setGeoserverURL(getFixture().getProperty("gs_url"));
    conf.setGeoserverUID(getFixture().getProperty("gs_user"));
    conf.setGeoserverPWD(getFixture().getProperty("gs_password"));
    conf.setDatastorePropertiesPath(datastoreFile.getAbsolutePath());
    conf.setDefaultNamespace(WORKSPACE);
    conf.setDefaultStyle("raster");
    conf.setCrs("EPSG:4326");

    return conf;
}

From source file:fr.adfab.magebeans.processes.CreateModuleProcess.java

protected void _createSetup() {
    String xpath = "resources/" + this.moduleNameLower + "_setup/setup/module";
    this._createNode(xpath, this.moduleName);
    xpath = "resources/" + this.moduleNameLower + "_setup/connection/use";
    this._createNode(xpath, "core_setup");
    String subDir = "sql/" + this.moduleNameLower + "_setup";
    this._createFolders(subDir);

    String setupFileName = subDir + "/mysql4-install-0.1.0.php";
    File setupFile = new File(setupFileName);
    String sourceFile = this._getResourceFile("mysql4-install-0.1.0.php");
    try {//  w  w w  .j  a  v a 2  s .c  o  m
        FileOutputStream fos = new FileOutputStream(setupFile);
        if (!setupFile.exists()) {
            setupFile.createNewFile();
        }
        fos.write(sourceFile.getBytes());
        fos.flush();
    } catch (FileNotFoundException ex) {
        Exceptions.printStackTrace(ex);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }

}