Example usage for android.content Context openFileOutput

List of usage examples for android.content Context openFileOutput

Introduction

In this page you can find the example usage for android.content Context openFileOutput.

Prototype

public abstract FileOutputStream openFileOutput(String name, @FileMode int mode) throws FileNotFoundException;

Source Link

Document

Open a private file associated with this Context's application package for writing.

Usage

From source file:com.anjalimacwan.receiver.WearPluginReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    try {//w  ww .  j a  va  2s .  c  o  m
        // Write note to disk
        FileOutputStream output = context.openFileOutput(String.valueOf(System.currentTimeMillis()),
                Context.MODE_PRIVATE);
        output.write(intent.getByteArrayExtra("note"));
        output.close();
    } catch (IOException e) {
        /* Gracefully fail */ }

    // Send broadcast to NoteListFragment to refresh list of notes
    Intent listNotesIntent = new Intent();
    listNotesIntent.setAction("com.anjalimacwan.LIST_NOTES");
    LocalBroadcastManager.getInstance(context).sendBroadcast(listNotesIntent);
}

From source file:com.notepadlite.WearPluginReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    try {//  w w w  .  j  av a  2  s  . c  om
        // Write note to disk
        FileOutputStream output = context.openFileOutput(String.valueOf(System.currentTimeMillis()),
                Context.MODE_PRIVATE);
        output.write(intent.getByteArrayExtra("note"));
        output.close();
    } catch (IOException e) {
    }

    // Send broadcast to NoteListFragment to refresh list of notes
    Intent listNotesIntent = new Intent();
    listNotesIntent.setAction("com.notepadlite.LIST_NOTES");
    LocalBroadcastManager.getInstance(context).sendBroadcast(listNotesIntent);
}

From source file:org.matrix.matrixandroidsdk.db.ConsoleMediasCache.java

/**
 * Save a bitmap to the local cache/*from  w w  w .j a va  2 s.c  o  m*/
 * it could be used for unsent media to allow them to be resent.
 * @param bitmap the bitmap to save
 * @param defaultFileName the filename is provided, if null, a filename will be generated
 * @return the media cache URL
 */
public static String saveBitmap(Bitmap bitmap, Context context, String defaultFileName) {
    String filename = "file" + System.currentTimeMillis();
    String cacheURL = null;

    try {
        if (null != defaultFileName) {
            File file = new File(defaultFileName);
            file.delete();

            filename = Uri.fromFile(file).getLastPathSegment();
        }

        FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);

        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);

        fos.flush();
        fos.close();

        cacheURL = Uri.fromFile(context.getFileStreamPath(filename)).toString();
    } catch (Exception e) {
    }

    return cacheURL;
}

From source file:com.lee.sdk.utils.Utils.java

/**
 * /*ww w. j  a  v  a 2s.  c o m*/
 * 
 * @param context Context Object
 * @param file ??
 * @param data ???
 * @param mode ?
 * @return ???
 */
public static boolean cache(Context context, String file, byte[] data, int mode) {
    boolean bResult = false;
    if (null == data) {
        data = new byte[0];
    }

    FileOutputStream fos = null;
    try {
        fos = context.openFileOutput(file, mode);
        fos.write(data);
        fos.flush();
        bResult = true;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (null != fos) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return bResult;
}

From source file:net.fizzl.redditengine.impl.PersistentCookieStore.java

/**
 * Save cookies to a file/*from  ww  w  . ja  v  a2s  . com*/
 */
private void save() {
    RedditApi api = DefaultRedditApi.getInstance();
    Context ctx = api.getContext();
    try {
        FileOutputStream fos = ctx.openFileOutput(cookiestore, Context.MODE_PRIVATE);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        SerializableCookieStore tempStore = new SerializableCookieStore();
        for (Cookie c : getCookies()) {
            tempStore.addCookie(c);
        }
        oos.writeObject(tempStore);
        oos.close();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:fr.simon.marquis.preferencesmanager.util.Utils.java

public static boolean savePreferences(PreferenceFile preferenceFile, String file, String packageName,
        Context ctx) {
    Log.d(TAG, String.format("savePreferences(%s, %s)", file, packageName));
    if (preferenceFile == null) {
        Log.e(TAG, "Error preferenceFile is null");
        return false;
    }//from   w ww  .ja  v a  2s . c o m

    if (!preferenceFile.isValid()) {
        Log.e(TAG, "Error preferenceFile is not valid");
        return false;
    }

    String preferences = preferenceFile.toXml();
    if (TextUtils.isEmpty(preferences)) {
        Log.e(TAG, "Error preferences is empty");
        return false;
    }

    File tmpFile = new File(ctx.getFilesDir(), TMP_FILE);
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                ctx.openFileOutput(TMP_FILE, Context.MODE_PRIVATE));
        outputStreamWriter.write(preferences);
        outputStreamWriter.close();
    } catch (IOException e) {
        Log.e(TAG, "Error writing temporary file", e);
        return false;
    }

    if (!RootTools.copyFile(tmpFile.getAbsolutePath(), file, true, false)) {
        Log.e(TAG, "Error copyFile from temporary file");
        return false;
    }

    if (!fixUserAndGroupId(ctx, file, packageName)) {
        Log.e(TAG, "Error fixUserAndGroupId");
        return false;
    }

    if (!tmpFile.delete()) {
        Log.e(TAG, "Error deleting temporary file");
    }

    RootTools.killProcess(packageName);
    Log.d(TAG, "Preferences correctly updated");
    return true;
}

From source file:com.mobilis.android.nfc.activities.MagTekFragment.java

public static void WriteSettings(Context context, String data, String file) throws IOException {
    FileOutputStream fos = null;//from   w w w  .  ja  v a  2 s  .co m
    OutputStreamWriter osw = null;
    fos = context.openFileOutput(file, Context.MODE_PRIVATE);
    osw = new OutputStreamWriter(fos);
    osw.write(data);
    osw.close();
    fos.close();
}

From source file:org.openremote.android.console.util.HTTPUtil.java

/**
 * Down load file and store it in local context.
 * //from   w  w  w.ja v a 2s.c om
 * @param serverUrl the current server url
 * @param fileName the file name for downloading
 * 
 * @return the int
 */
private static int downLoadFile(Context context, String serverUrl, String fileName) {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 5 * 1000);
    HttpConnectionParams.setSoTimeout(params, 5 * 1000);
    HttpClient client = new DefaultHttpClient(params);
    int statusCode = ControllerException.CONTROLLER_UNAVAILABLE;
    try {
        URL uri = new URL(serverUrl);
        if ("https".equals(uri.getProtocol())) {
            Scheme sch = new Scheme(uri.getProtocol(), new SelfCertificateSSLSocketFactory(context),
                    uri.getPort());
            client.getConnectionManager().getSchemeRegistry().register(sch);
        }
        HttpGet get = new HttpGet(serverUrl);
        SecurityUtil.addCredentialToHttpRequest(context, get);
        HttpResponse response = client.execute(get);
        statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == Constants.HTTP_SUCCESS) {
            FileOutputStream fOut = context.openFileOutput(fileName, Context.MODE_PRIVATE);
            InputStream is = response.getEntity().getContent();
            byte buf[] = new byte[1024];
            int len;
            while ((len = is.read(buf)) > 0) {
                fOut.write(buf, 0, len);
            }
            fOut.close();
            is.close();
        }
    } catch (MalformedURLException e) {
        Log.e("OpenRemote-HTTPUtil", "Create URL fail:" + serverUrl);
    } catch (IllegalArgumentException e) {
        Log.e("OpenRemote-IllegalArgumentException",
                "Download file " + fileName + " failed with URL: " + serverUrl, e);
    } catch (ClientProtocolException cpe) {
        Log.e("OpenRemote-ClientProtocolException",
                "Download file " + fileName + " failed with URL: " + serverUrl, cpe);
    } catch (IOException ioe) {
        Log.e("OpenRemote-IOException", "Download file " + fileName + " failed with URL: " + serverUrl, ioe);
    }
    return statusCode;
}

From source file:org.montanafoodhub.base.Hub.java

protected void writeToFile(Context context, String data, String fileName) {
    try {//from  w  w w  . j a v  a2  s  .  c  om
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                context.openFileOutput(fileName, Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    } catch (IOException e) {
        Log.e(HubInit.logTag, "File (" + fileName + ") write failed: " + e.toString());
    }
}

From source file:Main.java

private static File unzip(Context context, InputStream in) throws IOException {
    File tmpDb = null;// w w  w. ja  v a2 s.c om
    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;
}