简体   繁体   中英

android : best way to open a file in temprory memory

我有一个加密文件,解密时会在临时内存中打开该文件,当用户关闭文件时,他们的临时文件将被删除,该功能的实现方式是什么?

You cannot use external storage for the file since it will be available to whole world(what if user ejects SD card before you delete it?)

You should use internal storage so that you can remove it once the user is done. Use MODE_WORLD_READABLE so that user/other apps can only read it. When user is done, you can delete it.

String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
fos.write(string.getBytes());
fos.close();


File file = new File(FILENAME);
file.delete();

Good practice

Use internal storage and check out this: getCacheDir()


Bad practice

  1. create the file on your sdcard

     extStorageDirectory = Environment.getExternalStorageDirectory().toString(); File file = new File(extStorageDirectory, "filename.ext"); try { outStream = new FileOutputStream(file); //write data; outStream.flush(); outStream.close(); } 
  2. delete the file

     extStorageDirectory = Environment.getExternalStorageDirectory().toString(); File file = new File(extStorageDirectory, "filename.ext"); boolean deleted = file.delete(); 

As LAS_VEGAS said using external storage is a terrible idea!!

See this link for cache getCacheDir()

http://developer.android.com/guide/topics/data/data-storage.html#InternalCache

or use the normal internal storage with MODE_PRIVATE

ie

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

then after wards

deleteFile(FILENAME);

EDIT: MODE_PRIVATE would make it not accessible by other applications so maybe not a good idea !:(

But also if it has to decrypt a file and save it unencrypted, if someone really wanted at that file they could get it I'm sure since you're having it world readable for a while

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM