Example usage for java.io OutputStream close

List of usage examples for java.io OutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

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

Usage

From source file:Main.java

/**
 * Dump the database file to external storage
 *
 * @param packageName//ww  w. j a v a2s.co  m
 * @param fileName
 * @throws IOException
 */
public static void dumpDatabase(String packageName, String fileName) throws IOException {
    File dbFile = new File("/data/data/" + packageName + "/databases/" + fileName);
    if (dbFile.exists()) {
        FileInputStream fis = new FileInputStream(dbFile);
        String outFileName = Environment.getExternalStorageDirectory() + "/" + fileName;
        OutputStream output = new FileOutputStream(outFileName);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = fis.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
        output.flush();
        output.close();
        fis.close();
    }
}

From source file:com.knockturnmc.api.util.ConfigurationUtils.java

/**
 * Loads a mapped {@link Properties} file and applies the mapping provided by the {@link NamedProperties}.
 * If the desired file was not found in the datafolder, a default file will be copied from the classpath.
 *
 * @param classLoader the classloader to use for the default file
 * @param filename    the filename/*from  w ww.j ava  2 s . c  o  m*/
 * @param datafolder  the datafolder
 * @param mapping     the mapped file
 * @param <T>         the type of the mapped file
 * @return the loaded configuration mapping
 */
public static <T extends NamedProperties> T loadConfiguration(ClassLoader classLoader, String filename,
        File datafolder, Class<? extends T> mapping) {
    try {
        File file = getConfigFile(classLoader, filename, datafolder);
        Constructor<? extends T> constructor = mapping.getDeclaredConstructor();
        constructor.setAccessible(true);
        T properties = constructor.newInstance();
        FileInputStream stream = new FileInputStream(file);
        properties.load(stream);
        stream.close();

        OutputStream fos = new FileOutputStream(file);

        properties.store(fos, "Configuration for " + filename);
        fos.close();
        return properties;
    } catch (Exception e) {
        logger.warn("Failed to load configuration", e);
        throw new RuntimeException(e);
    }
}

From source file:com.nuvolect.deepdive.util.FileUtil.java

public static void writeFile(File file, String fileContents) {

    try {/*from ww w  .j a v  a2 s. c o  m*/
        OutputStream out = null;

        FileUtils.forceMkdirParent(file);

        out = new BufferedOutputStream(new FileOutputStream(file));

        out.write(fileContents.getBytes());

        if (out != null)
            out.close();
    } catch (IOException e) {
        LogUtil.log(FileUtil.class, "File write failed: " + e.toString());
    }
}

From source file:Main.java

public static boolean installPackage(Context context, InputStream in, String packageName) throws IOException {
    PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
    PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
            PackageInstaller.SessionParams.MODE_FULL_INSTALL);
    params.setAppPackageName(packageName);
    // set params
    int sessionId = packageInstaller.createSession(params);
    PackageInstaller.Session session = packageInstaller.openSession(sessionId);
    OutputStream out = session.openWrite("COSU", 0, -1);
    byte[] buffer = new byte[65536];
    int c;/*from   w ww . j a v  a  2  s .c  o  m*/
    while ((c = in.read(buffer)) != -1) {
        out.write(buffer, 0, c);
    }
    session.fsync(out);
    in.close();
    out.close();

    session.commit(createIntentSender(context, sessionId));
    return true;
}

From source file:com.microsoft.azure.hdinsight.sdk.storage.adls.WebHDFSUtils.java

public static void uploadFileToADLS(@NotNull IHDIStorageAccount storageAccount, @NotNull File localFile,
        @NotNull String remotePath, boolean overWrite) throws Exception {
    com.microsoft.azuretools.sdkmanage.AzureManager manager = AuthMethodManager.getInstance().getAzureManager();
    String tid = manager.getSubscriptionManager().getSubscriptionTenant(storageAccount.getSubscriptionId());
    String accessToken = manager.getAccessToken(tid);

    // TODO: accountFQDN should work for Mooncake
    String storageName = storageAccount.getName();
    ADLStoreClient client = ADLStoreClient.createClient(String.format("%s.azuredatalakestore.net", storageName),
            accessToken);/*from  ww w  .  j  a va2 s  . com*/
    OutputStream stream = null;
    try {
        stream = client.createFile(remotePath, IfExists.OVERWRITE);
        IOUtils.copy(new FileInputStream(localFile), stream);
        stream.flush();
        stream.close();
    } catch (ADLException e) {
        // ADLS operation may get a 403 when 'user' didn't have access to ADLS under Service Principle model
        // currently we didn't have a good way to solve this problem
        // we just popup the exception message for customers to guide customers login under interactive model
        if (e.httpResponseCode == 403
                || HttpStatusCode.valueOf(e.httpResponseMessage) == HttpStatusCode.FORBIDDEN) {
            throw new HDIException(
                    "Forbidden. Attached Azure DataLake Store is not supported in Automated login model. Please logout first and try Interactive login model",
                    403);
        }
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:com.microsoft.tfs.util.IOUtils.java

/**
 * Unconditionally closes the specified {@link OutputStream}, safely
 * handling any {@link IOException} thrown by the
 * {@link OutputStream#close()} method. If the log for this class is
 * properly configured, any such exception will be logged, but it will never
 * cause an exception to be thrown to the caller. This method is typically
 * called from a finally block in caller code.
 *
 * @param stream/*from w ww.  ja  v  a 2  s.  c o m*/
 *        the {@link OutputStream} to close (must not be <code>null</code>)
 */
public static void closeSafely(final OutputStream stream) {
    Check.notNull(stream, "stream"); //$NON-NLS-1$

    try {
        stream.close();
    } catch (final IOException e) {
        if (log.isTraceEnabled()) {
            log.trace("error closing OutputStream", e); //$NON-NLS-1$
        }
    }
}

From source file:Main.java

public static void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dst);

    // Transfer bytes from in to out
    byte[] buf = buffers.get();
    int len;/*  www .j a v  a  2 s .c  o m*/
    while ((len = in.read(buf)) > 0) {
        Thread.yield();
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
}

From source file:com.baasbox.service.push.providers.GCMServer.java

public static void validateApiKey(String apikey)
        throws MalformedURLException, IOException, PushInvalidApiKeyException {
    Message message = new Message.Builder().addData("message", "validateAPIKEY").build();
    Sender sender = new Sender(apikey);

    List<String> deviceid = new ArrayList<String>();
    deviceid.add("ABC");

    Map<Object, Object> jsonRequest = new HashMap<Object, Object>();
    jsonRequest.put(JSON_REGISTRATION_IDS, deviceid);
    Map<String, String> payload = message.getData();
    if (!payload.isEmpty()) {
        jsonRequest.put(JSON_PAYLOAD, payload);
    }//from   ww w  .jav a  2 s . c om
    String requestBody = JSONValue.toJSONString(jsonRequest);

    String url = com.google.android.gcm.server.Constants.GCM_SEND_ENDPOINT;
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();

    byte[] bytes = requestBody.getBytes();

    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(bytes.length);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Authorization", "key=" + apikey);
    OutputStream out = conn.getOutputStream();
    out.write(bytes);
    out.close();

    int status = conn.getResponseCode();
    if (status != 200) {
        if (status == 401) {
            throw new PushInvalidApiKeyException("Wrong api key");
        }
        if (status == 503) {
            throw new UnknownHostException();
        }
    }

}

From source file:Utils.java

public static void copyInputStream(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int len = in.read(buffer);
    while (len >= 0) {
        out.write(buffer, 0, len);/* w w w.  j a  v a 2  s  .  c o m*/
        len = in.read(buffer);
    }
    in.close();
    out.close();
}

From source file:Main.java

public static void takeScreenshot(String where, String name, View v) {

    // image naming and path to include sd card appending name you choose
    // for file//  ww w.  ja va2  s.  c om
    String mPath = where + "/" + name;

    // create bitmap screen capture
    Bitmap bitmap;
    View v1 = v.getRootView();
    v1.setDrawingCacheEnabled(true);
    bitmap = Bitmap.createBitmap(v1.getDrawingCache());
    v1.setDrawingCacheEnabled(false);

    OutputStream fout = null;
    File imageFile = new File(mPath);

    try {
        fout = new FileOutputStream(imageFile);
        bitmap.compress(Bitmap.CompressFormat.PNG, 90, fout);
        fout.flush();
        fout.close();

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

}