下面列出了android.content.Context#openFileOutput ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
}
}
}
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();
}
}
/**
* 释放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();
}
}
/**
* 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();
}
/**
* 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();
}
@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 */ }
}
}
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();
}
}
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();
}
}
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;
}
}
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");
}
}
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();
}
}
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
}
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());
}
}
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;
}
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();
}
}
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();
}
/** Opens {@link #TICL_STATE_FILENAME} for writing. */
private static FileOutputStream openStateFileForWriting(Context context)
throws FileNotFoundException {
return context.openFileOutput(TICL_STATE_FILENAME, Context.MODE_PRIVATE);
}
/** Opens {@link #TICL_STATE_FILENAME} for writing. */
private static FileOutputStream openStateFileForWriting(Context context)
throws FileNotFoundException {
return context.openFileOutput(TICL_STATE_FILENAME, Context.MODE_PRIVATE);
}
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();
}
/**
* 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)
+ "\"");
}
}