阅读:http://developer.android.com/guide/topics/data/data-storage.html

主要类型有:

Shared Preferences
    使用键值对存储
Internal Storage
    在内存存储私人数据。
External Storage
    在内存存储共用的数据。
SQLite Databases
    使用内部数据库。
Network Connection
    网络连接来存储。


使用Shared Preferences

可以通过以下方式获取SharedPreferences:

getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.
    getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.

public class Calc extends Activity {public static final String PREFS_NAME = "MyPrefsFile";@Overrideprotected void onCreate(Bundle state){super.onCreate(state);. . .// Restore preferencesSharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);boolean silent = settings.getBoolean("silentMode", false);setSilent(silent);}@Overrideprotected void onStop(){super.onStop();// We need an Editor object to make preference changes.// All objects are from android.context.ContextSharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);SharedPreferences.Editor editor = settings.edit();editor.putBoolean("silentMode", mSilentMode);// Commit the edits!
      editor.commit();}
}


使用Internal Storage

You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed.

  可以直接在私有的空间里直接存储文件,其他的程序和用户都无法访问它,当程序被卸载的时候,这些文件也会被删除。

——————————

String FILENAME = "hello_file";
String string = "hello world!";FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

MODE_PRIVATE 会创建一个私有的文件。 Other modes available are: MODE_APPEND, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE.

——————————

To read a file from internal storage:

  1. Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream.
  2. Read bytes from the file with read().
  3. Then close the stream with close().

Raw的访问方法:

If you want to save a static file in your application at compile time, save the file in your project res/raw/ directory. You can open it with openRawResource(), passing the R.raw.<filename> resource ID. This method returns an InputStream that you can use to read the file (but you cannot write to the original file).

Other useful methods

getFilesDir()
Gets the absolute path to the filesystem directory where your internal files are saved.
getDir()
Creates (or opens an existing) directory within your internal storage space.
deleteFile()
Deletes a file saved on the internal storage.
fileList()
Returns an array of files currently saved by your application.

使用external storage

我们可以先检测一下media的可用性:

boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();if (Environment.MEDIA_MOUNTED.equals(state)) {// We can read and write the mediamExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {// We can only read the mediamExternalStorageAvailable = true;mExternalStorageWriteable = false;
} else {// Something else is wrong. It may be one of many other states, but all we need//  to know is we can neither read nor writemExternalStorageAvailable = mExternalStorageWriteable = false;
}

——————————

If you're using API Level 8 or greater, use getExternalFilesDir() to open a File that represents the external storage directory where you should save your files. This method takes a type parameter that specifies the type of subdirectory you want, such as DIRECTORY_MUSIC and DIRECTORY_RINGTONES (pass null to receive the root of your application's file directory). This method will create the appropriate directory if necessary. By specifying the type of directory, you ensure that the Android's media scanner will properly categorize your files in the system (for example, ringtones are identified as ringtones and not music). If the user uninstalls your application, this directory and all its contents will be deleted.

If you're using API Level 7 or lower, use getExternalStorageDirectory(), to open a File representing the root of the external storage. You should then write your data in the following directory:

/Android/data/<package_name>/files/

The <package_name> is your Java-style package name, such as "com.example.android.app". If the user's device is running API Level 8 or greater and they uninstall your application, this directory and all its contents will be deleted.

  如果使用API8或者更高级的,可使用getExternalFilesDir()打开一个目录来存储文件,在参数里面可以有DIRECTORY_MUSIC 或者其他的,如果为null,则会选择属于本程序的目录,本程序的目录在卸载的时候会被删除掉。

  如果使用API8以下的,则需要使用getExternalStorageDirectory()并且手动选择目录。

——————————

如果想要创建能够共享的文件,程序被删除后文件依然存在,则可以选择以下方法:

In API Level 8 or greater, use getExternalStoragePublicDirectory(), passing it the type of public directory you want, such as DIRECTORY_MUSIC, DIRECTORY_PICTURES, DIRECTORY_RINGTONES, or others. This method will create the appropriate directory if necessary.

If you're using API Level 7 or lower, use getExternalStorageDirectory() to open a File that represents the root of the external storage, then save your shared files in one of the following directories:

  • Music/ - Media scanner classifies all media found here as user music.
  • Podcasts/ - Media scanner classifies all media found here as a podcast.
  • Ringtones/ - Media scanner classifies all media found here as a ringtone.
  • Alarms/ - Media scanner classifies all media found here as an alarm sound.
  • Notifications/ - Media scanner classifies all media found here as a notification sound.
  • Pictures/ - All photos (excluding those taken with the camera).
  • Movies/ - All movies (excluding those taken with the camcorder).
  • Download/ - Miscellaneous downloads.

使用数据库

使用数据库需要一个继承SQLiteOpenHelper的类,并覆盖oncreate方法来创建数据库。

public class DictionaryOpenHelper extends SQLiteOpenHelper {private static final int DATABASE_VERSION = 2;private static final String DICTIONARY_TABLE_NAME = "dictionary";private static final String DICTIONARY_TABLE_CREATE ="CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" +KEY_WORD + " TEXT, " +KEY_DEFINITION + " TEXT);";DictionaryOpenHelper(Context context) {super(context, DATABASE_NAME, null, DATABASE_VERSION);}@Overridepublic void onCreate(SQLiteDatabase db) {db.execSQL(DICTIONARY_TABLE_CREATE);}
}

想要更好的学习,可以参照官方例子:

For sample apps that demonstrate how to use SQLite databases in Android, see the Note Pad and Searchable Dictionary applications.

例子在本地,路径是:android-sdk\docs\guide\samples

转载于:https://www.cnblogs.com/yutoulck/p/3388490.html

Storage Options相关推荐

  1. html5 dom storage,Client-side data storing,DOM storage or HTML5 Local Storage?

    问题 Im really confused when thinking about my requirement to store data locally for offline viewing.N ...

  2. ZF2 Session简单使用(Zend\Authentication\Storage\Session.php)

    ZF2  Session 第一次记录,用词不当或说法不正确,请留言! 在zf2中要简单使用session,你需要引入的文件: use Zend\Authentication\Storage\Sessi ...

  3. Android手机的 storage

    老外的一段解释 -------------------------------------------------------------------------------------------- ...

  4. CentOS6.5上源码安装MongoDB3.2.1

    CentOS6.5上源码安装MongoDB3.2.1 [日期:2016-01-27] 来源:Linux社区  作者:darren-lee [字体:大 中 小] 1.环境准备: 1 mkdir /hom ...

  5. VMware10 —— 安装CentOS7(图解)

    若您想在VMware 10下安装 Centos7操作系统可以查看此文档 (32位.64位文章内有说明:本文主要以32位安装为主[32位VMware,32位Centos7镜像]) 基础设置介绍: 计算机 ...

  6. docker 的mysql镜像使用手册 官网原文 日期2017-05-25

    官网地址点击这里 Supported tags and respective Dockerfile links 8.0.1,8.0, 8 (8.0/Dockerfile) 5.7.18,5.7, 5, ...

  7. Management of your data

    Management of your data 文章目录 Management of your data Intro Session data Data lifecycle Why Areas of ...

  8. Linux RH5平台下使用Oracle ASM创建数据库

    一.安装配置先决条件 1.安装oracleasm支持包 创建asm数据库,首先需要ASMLib驱动程序包,可以从相关的网站下载到和操作系统对应的rpm文件,分别为oracleasm-support-2 ...

  9. 算法竞赛训练指南代码仓库_数据仓库综合指南

    算法竞赛训练指南代码仓库 重点 (Top highlight) As a data scientist, it's valuable to have some idea of fundamental ...

最新文章

  1. XCODE 4.5 IOS多语言设置
  2. Nature子刊:残留DNA在土壤中含量丰富并且模糊了对土壤生物多样性的估计
  3. 对于一些手机内存概念的思考、深入理解java的finalize,对于内存优化的小总结...
  4. Python编程基础:第二十四节 作用域Scope
  5. 苹果隐藏应用_使用iMazing导出苹果设备中的录音文件
  6. Unknown opcode
  7. 【CodeForces - 298D】Fish Weight (OAE思想,思维)
  8. python crm_Python CRM项目一
  9. 产品经理如何应对一句话需求
  10. springboot入门介绍
  11. 蚂蚁上市员工人均一套大 House,阿里程序员身价和这匹配吗?
  12. ElasticSearch 集群监控
  13. python中的itemgetter函数
  14. 关于c++初始化原理与性能的讨论
  15. 今天安利一个超牛叉的黑客入侵的特效网页,我第一次打开就被惊艳到了
  16. PLC编程从入门到精通视频教程【副业学习会】
  17. oracle instant client 配置,oracle instantclient配置
  18. C题:无线充电电动小车(本科)--2018年TI杯大学生电子设计竞赛
  19. 离获得支付牌照还有多远?今日头条申请“字节支付”商标
  20. 丽台显卡测试软件,领先A卡62% 丽台7系显卡对比测试

热门文章

  1. std::string用法总结
  2. UNIX网络编程——客户/服务器程序设计示范(一)
  3. 对于2.3版的OpenCV的IplImage,最好不要直接操作其imageData成员~
  4. VC中栈溢出/Stack overflow怎么办?
  5. pythonhistogram教程_OpenCV-Python 直方图-4:直方图反投影 | 二十九
  6. wchar_t*,wchar_t,wchat_t数组,char,char*,char数组,std::string,std::wstring,CString....转换
  7. [原]flash研究(三)——Falsh与JavaScript交互
  8. [20180306]关于DEFERRED ROLLBACK2.txt
  9. Web安全实践(2)基于http的web架构剖析
  10. /etc/issue、shutdown命令详解