Example usage for java.io FileOutputStream close

List of usage examples for java.io FileOutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this file output stream and releases any system resources associated with this stream.

Usage

From source file:Main.java

private static boolean copyFile(File assetFile, File storageFile, AssetManager assetManager) {
    try {/*from ww  w .ja v  a2  s .co m*/
        InputStream in = assetManager.open(assetFile.getPath());
        FileOutputStream out = new FileOutputStream(storageFile);
        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        out.close();
        return true;
    } catch (FileNotFoundException e) {
        return false;
    } catch (IOException e) {
        return false;
    }
}

From source file:com.github.ajasmin.telususageandroidwidget.TelusReportFetcher.java

private static void fetchUsageSummaryPage(DefaultHttpClient httpclient, PreferencesData prefs)
        throws NetworkErrorException {
    try {/*from ww w  .  jav a2s . com*/
        final String url = "https://mobile.telus.com/index.htm";
        HttpPost httpPost = new HttpPost(url);

        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        if (prefs.subscriber != null) {
            formparams.add(new BasicNameValuePair("subscriber", prefs.subscriber));
        }

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
        httpPost.setEntity(entity);

        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();

        // Save the page to disk
        String fileName = Integer.toString(prefs.appWidgetId);
        FileOutputStream fileOutput = MyApp.getContext().openFileOutput(fileName, Context.MODE_PRIVATE);
        responseEntity.writeTo(fileOutput);
        fileOutput.close();
    } catch (IOException e) {
        throw new NetworkErrorException("Error fetching data from Telus website", e);
    }
}

From source file:ch.ethz.inf.vs.android.g54.a4.util.SnapshotCache.java

public static void storeSnapshot(List<WifiReading> readings, String fileName, Context c) {

    String state = Environment.getExternalStorageState();

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        // We can read and write the external storage
        try {//from w ww . j a v  a2s .c o m
            JSONArray json = readingsToJson(readings);
            File root = c.getExternalCacheDir();
            File jsonFile = new File(root, constructFileName(fileName));
            FileOutputStream out;
            out = new FileOutputStream(jsonFile);
            out.write(json.toString().getBytes());
            out.close();
            U.showToast(constructFileName(fileName));
            Log.d(TAG, "Successfully stored snapshot to SDCard");
        } catch (Exception e) {
            U.showToast("Could not save the snapshot on the SDCard.");
            Log.e(TAG, "Could not save the snapshot on the SDCard.", e);
        }
    } else {
        U.showToast("Cannot write to external storage.");
    }
}

From source file:com.bluexml.side.m2.repositoryBuilder.Builder.java

private static void writePomFile(File pomFile, List<ModuleConstraint> res)
        throws Exception, JDOMException, FileNotFoundException, IOException {
    Document pom = PluginsUtils.buildJdomDocument(pomFile);
    // search existing dependencies node
    XPath xpa = XPath.newInstance("/project/dependencies");
    Element deps = (Element) xpa.selectSingleNode(pom.getRootElement());
    if (deps == null) {
        deps = new Element("dependencies");
        pom.getRootElement().addContent(deps);
    }//from   w  w  w  . j a  v a  2s. com
    // add dependencies
    for (ModuleConstraint moduleConstraint : res) {
        Element dep = new Element("dependency");

        Element groupId = new Element("groupId").setText(moduleConstraint.getGroupId());
        Element artifactId = new Element("artifactId").setText(moduleConstraint.getArtifactId());
        Element version = new Element("version").setText(moduleConstraint.getVersionRange());
        Element type = new Element("type").setText(moduleConstraint.getModuleType());
        Element scope = new Element("scope").setText("compile");

        dep.addContent(groupId);
        dep.addContent(artifactId);
        dep.addContent(version);
        dep.addContent(type);
        dep.addContent(scope);
        deps.addContent(dep);
        System.out.println("added :" + moduleConstraint);
    }
    // save changes
    org.jdom.output.XMLOutputter out = new XMLOutputter();
    Format format = Format.getPrettyFormat();
    out.setFormat(format);
    FileOutputStream outStream = new FileOutputStream(pomFile);
    out.output(pom, outStream);
    outStream.close();
}

From source file:net.giovannicapuano.visualnovel.Memory.java

public static boolean putKeyValues(Context context, Hashtable<String, String> keyvalues) {
    try {/*ww w  .j a  v  a2 s  . c om*/
        JSONObject json = new JSONObject();

        for (Entry<String, String> entry : keyvalues.entrySet())
            json.put(entry.getKey(), entry.getValue());

        FileOutputStream fos = context.openFileOutput(KEYVALUES, Context.MODE_PRIVATE);
        fos.write(json.toString().getBytes());
        fos.flush();
        fos.close();

        return true;
    } catch (Exception e) {
        Utils.error(e);
        Utils.error(context, context.getString(R.string.error_saving_game));
        return false;
    }
}

From source file:org.limy.common.graph.GraphUtils.java

/**
 * PNG??????/*from w ww  . j  av  a  2s  . c om*/
 * @param chart ?
 * @param pngFile png
 * @param width width
 * @param height height
 * @throws IOException I/O
 */
public static void writeImagePng(JFreeChart chart, File pngFile, int width, int height) throws IOException {

    BufferedImage image = chart.createBufferedImage(width, height);
    FileOutputStream outStream = new FileOutputStream(pngFile);
    try {
        PngEncoder pngEncoder = new PngEncoder(image);
        pngEncoder.setCompressionLevel(9);
        outStream.write(pngEncoder.pngEncode());
    } finally {
        outStream.close();
    }
}

From source file:org.apache.hadoop.gateway.GatewayAdminFuncTest.java

public static void setupGateway() throws Exception {

    File targetDir = new File(System.getProperty("user.dir"), "target");
    File gatewayDir = new File(targetDir, "gateway-home-" + UUID.randomUUID());
    gatewayDir.mkdirs();/*  w  w  w .  jav a 2s  .c  o m*/

    GatewayTestConfig testConfig = new GatewayTestConfig();
    config = testConfig;
    testConfig.setGatewayHomeDir(gatewayDir.getAbsolutePath());

    File topoDir = new File(testConfig.getGatewayTopologyDir());
    topoDir.mkdirs();

    File deployDir = new File(testConfig.getGatewayDeploymentDir());
    deployDir.mkdirs();

    File descriptor = new File(topoDir, "test-cluster.xml");
    FileOutputStream stream = new FileOutputStream(descriptor);
    createTopology().toStream(stream);
    stream.close();

    DefaultGatewayServices srvcs = new DefaultGatewayServices();
    Map<String, String> options = new HashMap<>();
    options.put("persist-master", "false");
    options.put("master", "password");
    try {
        srvcs.init(testConfig, options);
    } catch (ServiceLifecycleException e) {
        e.printStackTrace(); // I18N not required.
    }
    gateway = GatewayServer.startGateway(testConfig, srvcs);
    MatcherAssert.assertThat("Failed to start gateway.", gateway, notNullValue());

    LOG.info("Gateway port = " + gateway.getAddresses()[0].getPort());

    gatewayUrl = "http://localhost:" + gateway.getAddresses()[0].getPort() + "/" + config.getGatewayPath();
    clusterUrl = gatewayUrl + "/test-cluster";
}

From source file:com.ginstr.android.service.opencellid.library.data.ApiKeyHandler.java

/**
 * stores newly generated key into the file
 * @param key generated by the server//from   ww w . j  a v  a  2  s  . c  om
 * @param testMode Defines in which file the key will be stored
 */
private static void writeApiKeyToFile(String key, boolean testMode) {
    String keyFilePath = testMode ? API_KEY_FILE_TEST_DEFAULT : API_KEY_FILE_DEFAULT;

    File keyFile = new File(keyFilePath);

    try {
        FileOutputStream fos = new FileOutputStream(keyFile, false);
        fos.write(key.getBytes());
        fos.flush();
        fos.close();
    } catch (Exception e) {
        Log.e(ApiKeyHandler.class.getSimpleName(), "Error writing key to file", e);
    }
}

From source file:org.apache.hadoop.gateway.GatewaySampleFuncTest.java

public static void setupGateway() throws Exception {

    File targetDir = new File(System.getProperty("user.dir"), "target");
    File gatewayDir = new File(targetDir, "gateway-home-" + UUID.randomUUID());
    gatewayDir.mkdirs();/*from  w w w  .  java2s.  co m*/

    GatewayTestConfig testConfig = new GatewayTestConfig();
    config = testConfig;
    testConfig.setGatewayHomeDir(gatewayDir.getAbsolutePath());

    File topoDir = new File(testConfig.getGatewayTopologyDir());
    topoDir.mkdirs();

    File deployDir = new File(testConfig.getGatewayDeploymentDir());
    deployDir.mkdirs();

    File descriptor = new File(topoDir, "test-cluster.xml");
    FileOutputStream stream = new FileOutputStream(descriptor);
    createTopology().toStream(stream);
    stream.close();

    DefaultGatewayServices srvcs = new DefaultGatewayServices();
    Map<String, String> options = new HashMap<>();
    options.put("persist-master", "false");
    options.put("master", "password");
    try {
        srvcs.init(testConfig, options);
    } catch (ServiceLifecycleException e) {
        e.printStackTrace(); // I18N not required.
    }

    gateway = GatewayServer.startGateway(testConfig, srvcs);
    MatcherAssert.assertThat("Failed to start gateway.", gateway, notNullValue());

    LOG.info("Gateway port = " + gateway.getAddresses()[0].getPort());

    gatewayUrl = "http://localhost:" + gateway.getAddresses()[0].getPort() + "/" + config.getGatewayPath();
    clusterUrl = gatewayUrl + "/test-cluster";
}

From source file:Main.java

public static void addCertToKnownServersStore(Certificate cert, Context context)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    KeyStore knownServers = getKnownServersStore(context);
    knownServers.setCertificateEntry(Integer.toString(cert.hashCode()), cert);
    FileOutputStream fos = null;
    try {//  w  w  w . ja  v a  2 s .c o  m
        fos = context.openFileOutput(LOCAL_TRUSTSTORE_FILENAME, Context.MODE_PRIVATE);
        knownServers.store(fos, LOCAL_TRUSTSTORE_PASSWORD.toCharArray());
    } finally {
        fos.close();
    }
}