Andorid存储之SharedPreferences & File
Andorid存储之SharedPreferences & File
比较简单,所以直接看代码把。
/** * Android的四种存储方式: * sharedPreferences * SQLite File * Content Provider */ public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /** * SharedPreferences * 是一种轻型的数据存储方式, * 本质是基于XML文件存储key-value键值对数据(保存为一个XML文件), * 通常用来存储一些简单的配置信息 * (通常用来保存字符串和整型之类的简单数据类型) * 如果存储信息很少,用数据库保存效率低很多,用这种比较合适,遍历数据比较难 * SharedPreferences对象本身只能获取数据 * 修改存储是通过SharedPreferences.Editor对象实现的 * 实现SharedPreferences存储的步骤: * (1)获得SharedPreferences对象 * (2)获得SharedPreferences.Editor对象 * (3)通过Editor接口的putXxx方法保存key-value对其中Xxx表示不同的数据类型 * (4)通过Editor接口的commit方法保存key-value对 */ //实现SharedPreferences存储的步骤:(4步) //(1)获得SharedPreferences对象 //SharedPreferences Pref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); SharedPreferences Pref = getSharedPreferences("myPref", MODE_PRIVATE);//名字,只能给这个程序使用 //(2)获得SharedPreferences.Editor对象 Editor edior = Pref.edit(); //(3)通过Editor接口的putXxx方法保存key-value对其中Xxx表示不同的数据类型 edior.putString("name", "LWJ"); edior.putInt("age", 21); edior.putString("sex", "boy"); edior.remove("sex"); //(4)通过Editor接口的commit方法保存key-value对 edior.commit(); System.out.println(Pref.getString("name","")); System.out.println(Pref.getInt("age",0)); //注意,我们数据保存都得保存在root/data/data/包名下,这样删除App后,所有数据才会一起删除 File file = new File("/mnt/sdcard/text");//打开文件 if(file.exists()){//文件已存在 file.delete();//文件删除 } else { try { file.createNewFile();//在该路径创建此文件 } catch (IOException e) { e.printStackTrace(); } } File file1 = this.getFilesDir();//获得程序默认存储路径 File file2 = this.getCacheDir();//获得程序默认缓存路径,如果手机内存不足,程序会自动删除缓存文件内容 /** * MODE_PRIVATE:默认操作模式,表示该文件是私有的,只能被该程序所用,该模式下写入内容会覆盖原内容。 * MODE_APPEND:如果文件不存在,创建,如果存在就往文件内容后面追加内容。 * 可以用+设置多种权限 */ File file3 = this.getDir("LWJ", MODE_PRIVATE);//在data/data/包名下创建一个LWJ目录,权限 File file4 = this.getExternalFilesDir(ACCESSIBILITY_SERVICE);//得到外部存储文件位置 File[] file5 = this.getExternalCacheDirs();//得到外部缓存文件位置 try { FileOutputStream output = openFileOutput("a.txt", MODE_PRIVATE);//把数据保存到文件a.txt中 try { output.write("buffer".getBytes()); output.close(); } catch (IOException e) { e.printStackTrace(); } FileInputStream input = openFileInput("a.txt");//读取a.txt的数据 try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while((len = input.read(buffer))!= -1){ baos.write(buffer,0,len); } String s = baos.toString(); input.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } }
如果有什么错误,或者我理解错误或不当的,恳请大家纠正,谢谢!嘻嘻嘻~