Java Code Examples for android.content.Context#openFileOutput()

The following examples show how to use android.content.Context#openFileOutput() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AppEventsLogger.java    From Abelana-Android with Apache License 2.0 6 votes vote down vote up
static void saveAppSessionInformation(Context context) {
    ObjectOutputStream oos = null;

    synchronized (staticLock) {
        if (hasChanges) {
            try {
                oos = new ObjectOutputStream(
                        new BufferedOutputStream(
                                context.openFileOutput(
                                        PERSISTED_SESSION_INFO_FILENAME,
                                        Context.MODE_PRIVATE)
                        )
                );
                oos.writeObject(appSessionInfoMap);
                hasChanges = false;
                Logger.log(LoggingBehavior.APP_EVENTS, "AppEvents", "App session info saved");
            } catch (Exception e) {
                Log.d(TAG, "Got unexpected exception: " + e.toString());
            } finally {
                Utility.closeQuietly(oos);
            }
        }
    }
}
 
Example 2
Source File: DataProvider.java    From callmeter with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Upgrade table.
 *
 * @param db {@link SQLiteDatabase}
 * @throws IOException IOException
 */
public static void onUpgrade(final Context context, final SQLiteDatabase db)
        throws IOException {
    Log.w(TAG, "Upgrading table: " + TABLE);

    String fn = TABLE + ".bak";
    context.deleteFile(fn);
    ObjectOutputStream os = new ObjectOutputStream(context.openFileOutput(fn,
            Context.MODE_PRIVATE));
    backup(db, TABLE, PROJECTION, null, null, null, os);
    os.close();
    ObjectInputStream is = new ObjectInputStream(context.openFileInput(fn));
    onCreate(db);
    reload(db, TABLE, is);
    is.close();
}
 
Example 3
Source File: DataProvider.java    From callmeter with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Upgrade table.
 *
 * @param db {@link SQLiteDatabase}
 * @throws IOException IOException
 */
public static void onUpgrade(final Context context, final SQLiteDatabase db)
        throws IOException {
    Log.w(TAG, "Upgrading table: " + TABLE);

    String fn = TABLE + ".bak";
    context.deleteFile(fn);
    ObjectOutputStream os = new ObjectOutputStream(context.openFileOutput(fn,
            Context.MODE_PRIVATE));
    backup(db, TABLE, PROJECTION, null, null, null, os);
    os.close();
    ObjectInputStream is = new ObjectInputStream(context.openFileInput(fn));
    onCreate(db);
    reload(db, TABLE, is);
    is.close();
}
 
Example 4
Source File: AssetUtils.java    From ShellAndroid with Apache License 2.0 6 votes vote down vote up
/**
 * 释放Asset里面的文件
 * @param context
 * @param fileName
 * @param checkFile 如果检测文件,则在文件存在的时候不进行释放
 * @throws IOException
 */
public static void extractAsset(Context context, String fileName, boolean checkFile) throws IOException{
	if (!checkFile || !isFileExist(context, fileName)){
		AssetManager manager = context.getAssets();
		InputStream in = manager.open(fileName);
		OutputStream out = context.openFileOutput(fileName, Context.MODE_PRIVATE);
		BufferedOutputStream bout = new BufferedOutputStream(out);
		int iByte = -1;
		while ((iByte = in.read()) != -1){
			bout.write(iByte);
		}
		bout.flush();
		bout.close();
		out.close();
		in.close();
	}
}
 
Example 5
Source File: RealmComic.java    From Easy_xkcd with Apache License 2.0 6 votes vote down vote up
public static void saveOfflineBitmap(Response response, PrefHelper prefHelper, int comicNumber, Context context) {
    String comicFileName = comicNumber + ".png"; // TODO: Some early comics are .jpg
    try {
        File sdCard = prefHelper.getOfflinePath();
        File dir = new File(sdCard.getAbsolutePath() + RealmComic.OFFLINE_PATH);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try (FileOutputStream fos = new FileOutputStream(sdCard.getAbsolutePath() + RealmComic.OFFLINE_PATH + "/" + comicFileName)) {
            fos.write(response.body().bytes());
        }
    } catch (Exception e) {
        Timber.e("Error at comic %d: Saving to external storage failed: %s", comicNumber, e.getMessage());
        try (FileOutputStream fos = context.openFileOutput(String.valueOf(comicNumber), Context.MODE_PRIVATE)) {
            fos.write(response.body().bytes());
        } catch (Exception e2) {
            Timber.e("Error at comic %d: Saving to internal storage failed: %s", comicNumber, e2.getMessage());
        }
    } finally {
        response.body().close();
    }
}
 
Example 6
Source File: Service.java    From Pocket-Plays-for-Twitch with GNU General Public License v3.0 5 votes vote down vote up
public static void saveImageToStorage(Bitmap image, String key, Context context) {
    try {
        // Create an ByteArrayOutputStream and feed a compressed bitmap image in it
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.PNG, 100, byteStream); // PNG as only format with transparency

        // Create a FileOutputStream with out key and set the mode to private to ensure
        // Only this app and read the file. Write out ByteArrayOutput to the file and close it
        FileOutputStream fileOut = context.openFileOutput(key, Context.MODE_PRIVATE);
        fileOut.write(byteStream.toByteArray());
        byteStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 7
Source File: Service.java    From Twire with GNU General Public License v3.0 5 votes vote down vote up
public static void saveImageToStorage(Bitmap image, String key, Context context) {
    try {
        // Create an ByteArrayOutputStream and feed a compressed bitmap image in it
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.PNG, 100, byteStream); // PNG as only format with transparency

        // Create a FileOutputStream with out key and set the mode to private to ensure
        // Only this app and read the file. Write out ByteArrayOutput to the file and close it
        FileOutputStream fileOut = context.openFileOutput(key, Context.MODE_PRIVATE);
        fileOut.write(byteStream.toByteArray());
        byteStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 8
Source File: U.java    From SecondScreen with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("HardwareIds")
public static void initPrefs(Context context) {
    // Gather display metrics
    getDisplayMetrics(context);

    // Set some default preferences
    SharedPreferences prefMain = getPrefMain(context);
    SharedPreferences.Editor editor = prefMain.edit();
    editor.putBoolean("first-run", true);
    editor.putBoolean("safe_mode", true);
    editor.putString("android_id", Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID));
    editor.putBoolean("hdmi", true);
    editor.putString("notification_action", "quick-actions");
    editor.putBoolean("show-welcome-message", !isBlissOs(context));
    editor.apply();

    // Create default profile for BlissOS
    if(isBlissOs(context)) {
        String filename = String.valueOf(System.currentTimeMillis());
        String profileName = context.getResources().getString(R.string.blissos_default);

        createProfileFromTemplate(context, profileName, 3, getPrefSaved(context, filename));

        // Write the String to a new file with filename of current milliseconds of Unix time
        try {
            FileOutputStream output = context.openFileOutput(filename, Context.MODE_PRIVATE);
            output.write(profileName.getBytes());
            output.close();
        } catch (IOException e) { /* Gracefully fail */ }
    }
}
 
Example 9
Source File: TopApps.java    From Taskbar with Apache License 2.0 5 votes vote down vote up
private boolean save(Context context) {
    try {
        FileOutputStream fileOutputStream = context.openFileOutput("TopApps", Context.MODE_PRIVATE);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);

        objectOutputStream.writeObject(this);

        objectOutputStream.close();
        fileOutputStream.close();

        return true;
    } catch (IOException e) {
        return false;
    }
}
 
Example 10
Source File: Application.java    From Passbook with Apache License 2.0 5 votes vote down vote up
void saveData(Context context) {
    if(mLocalVersion <= Options.mSyncVersion) {
        mLocalVersion++;
    }
    byte[] cipher = mCrypto.encrypt(mAccountManager.getBytes());
    byte[] header = FileHeader.build(APP_VERSION, mCrypto.getIterationCount(),
            Crypto.SALT_LENGTH, mCrypto.getIvLength(), mLocalVersion);
    byte[] keyInfo = mCrypto.getSaltAndIvBytes();
    try {
        FileOutputStream fos = context.openFileOutput(DATA_FILE, Context.MODE_PRIVATE);
        fos.write(header);
        fos.write(keyInfo);
        fos.write(cipher);
        int size = header.length + keyInfo.length + cipher.length;
        if (mBuffer == null || mBuffer.length != size) {
            mBuffer = new byte[size];
        }
        System.arraycopy(header, 0, mBuffer, 0, header.length);
        System.arraycopy(keyInfo, 0, mBuffer, header.length, keyInfo.length);
        System.arraycopy(cipher, 0, mBuffer, header.length + keyInfo.length, cipher.length);
        fos.close();
        mFileHeader = FileHeader.parse(mBuffer);
        mAccountManager.onSaved();
    }catch (FileNotFoundException e) {
        Log.w("Passbook", "File not found");
    }
    catch(IOException ioe) {
        Log.e("Passbook", "IOException");
    }
}
 
Example 11
Source File: Video.java    From dtube-mobile-unofficial with Apache License 2.0 5 votes vote down vote up
private static void saveRecentsList(VideoArrayList videos, Context c){
    FileOutputStream fos;
    try {
        fos = c.openFileOutput("recentsVideos", Context.MODE_PRIVATE);
        ObjectOutputStream os = new ObjectOutputStream(fos);
        os.writeObject(videos);
        os.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
 
Example 12
Source File: EasySaveUtil.java    From Easy-Save with MIT License 5 votes vote down vote up
private static boolean writeObject(Context context, String key, String object) {
    try {
        //salvando o objeto na memória do Android
        FileOutputStream fos = context.openFileOutput(key, Context.MODE_PRIVATE);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(object);
        oos.close();
        fos.close();

    } catch (IOException e) {
        e.printStackTrace();
        return false; // caso não seja possível salvar, retornar falso
    }
    return true; // caso seja possível salvar, retornar verdadeiro
}
 
Example 13
Source File: Util.java    From scanvine-android with MIT License 5 votes vote down vote up
public static void WriteToFile(Context context, String filename, String data) {
    try {
    	FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos);
        outputStreamWriter.write(data);
        outputStreamWriter.flush();
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    } 
}
 
Example 14
Source File: ZenJSONUtil.java    From zen4android with MIT License 5 votes vote down vote up
public static void WriteJSONToFile(String fileName, String json) {
	try {
		Context context = ZenApplication.getAppContext();
		OutputStream output = context.openFileOutput(fileName, Context.MODE_PRIVATE);
		output.write(json.getBytes("utf-8"));
		output.close();
		
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 15
Source File: FileUtils.java    From freemp with Apache License 2.0 5 votes vote down vote up
public static boolean writeObject(String filename, Context context, Object o) {
    boolean success = false;
    try {
        FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
        ObjectOutputStream os = new ObjectOutputStream(fos);
        os.writeObject(o);
        fos.flush();
        os.close();
        success = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return success;
}
 
Example 16
Source File: PlumbleTrustStore.java    From Plumble with GNU General Public License v3.0 4 votes vote down vote up
public static void saveTrustStore(Context context, KeyStore store) throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException {
    FileOutputStream fos = context.openFileOutput(STORE_FILE, Context.MODE_PRIVATE);
    store.store(fos, STORE_PASS.toCharArray());
    fos.close();
}
 
Example 17
Source File: UpdateHandler.java    From Indic-Keyboard with Apache License 2.0 4 votes vote down vote up
/**
 * Handle a word list: put it in its right place, and update the passed content values.
 * @param context the context for opening files.
 * @param inputStream an input stream pointing to the downloaded data. May not be null.
 *  Will be closed upon finishing.
 * @param downloadRecord the content values to fill the file name in.
 * @throws IOException if files can't be read or written.
 * @throws BadFormatException if the md5 checksum doesn't match the metadata.
 */
private static void handleWordList(final Context context,
        final InputStream inputStream, final DownloadRecord downloadRecord)
        throws IOException, BadFormatException {

    // DownloadManager does not have the ability to put the file directly where we want
    // it, so we had it download to a temporary place. Now we move it. It will be deleted
    // automatically by DownloadManager.
    DebugLogUtils.l("Downloaded a new word list :", downloadRecord.mAttributes.getAsString(
            MetadataDbHelper.DESCRIPTION_COLUMN), "for", downloadRecord.mClientId);
    PrivateLog.log("Downloaded a new word list with description : "
            + downloadRecord.mAttributes.getAsString(MetadataDbHelper.DESCRIPTION_COLUMN)
            + " for " + downloadRecord.mClientId);

    final String locale =
            downloadRecord.mAttributes.getAsString(MetadataDbHelper.LOCALE_COLUMN);
    final String destinationFile = getTempFileName(context, locale);
    downloadRecord.mAttributes.put(MetadataDbHelper.LOCAL_FILENAME_COLUMN, destinationFile);

    FileOutputStream outputStream = null;
    try {
        outputStream = context.openFileOutput(destinationFile, Context.MODE_PRIVATE);
        copyFile(inputStream, outputStream);
    } finally {
        inputStream.close();
        if (outputStream != null) {
            outputStream.close();
        }
    }

    // TODO: Consolidate this MD5 calculation with file copying above.
    // We need to reopen the file because the inputstream bytes have been consumed, and there
    // is nothing in InputStream to reopen or rewind the stream
    FileInputStream copiedFile = null;
    final String md5sum;
    try {
        copiedFile = context.openFileInput(destinationFile);
        md5sum = MD5Calculator.checksum(copiedFile);
    } finally {
        if (copiedFile != null) {
            copiedFile.close();
        }
    }
    if (TextUtils.isEmpty(md5sum)) {
        return; // We can't compute the checksum anyway, so return and hope for the best
    }
    if (!md5sum.equals(downloadRecord.mAttributes.getAsString(
            MetadataDbHelper.CHECKSUM_COLUMN))) {
        context.deleteFile(destinationFile);
        throw new BadFormatException("MD5 checksum check failed : \"" + md5sum + "\" <> \""
                + downloadRecord.mAttributes.getAsString(MetadataDbHelper.CHECKSUM_COLUMN)
                + "\"");
    }
}
 
Example 18
Source File: TiclStateManager.java    From android-chromium with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/** Opens {@link #TICL_STATE_FILENAME} for writing. */
private static FileOutputStream openStateFileForWriting(Context context)
    throws FileNotFoundException {
  return context.openFileOutput(TICL_STATE_FILENAME, Context.MODE_PRIVATE);
}
 
Example 19
Source File: TiclStateManager.java    From android-chromium with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/** Opens {@link #TICL_STATE_FILENAME} for writing. */
private static FileOutputStream openStateFileForWriting(Context context)
    throws FileNotFoundException {
  return context.openFileOutput(TICL_STATE_FILENAME, Context.MODE_PRIVATE);
}
 
Example 20
Source File: Utility.java    From ExpressHelper with GNU General Public License v3.0 4 votes vote down vote up
public static void saveFile(Context context, String name, String text) throws IOException {
	FileOutputStream fos = context.openFileOutput(name, Context.MODE_PRIVATE);
	fos.write(text.getBytes());
	fos.close();
}