Welcome 微信登录

首页 / 移动开发 / Android / Android应用开发中数据的保存方式总结

一、保存文件到手机内存

/** * 保存数据到手机rom的文件里面. * @param context 应用程序的上下文 提供环境 * @param name 用户名 * @param password 密码 * @throws Exception */public static void saveToRom(Context context, String name , String password) throws Exception{//File file = new File("/data/data/com.itheima.login/files/info.txt");File file = new File(context.getFilesDir(),"info.txt");//该文件在data下的files文件夹下getCacheDir()在cache文件夹下 文件大小不要超过1MbFileOutputStream fos = new FileOutputStream(file);String txt = name+":"+password;fos.write(txt.getBytes());fos.flush();fos.close();}
/** * 获取保存的数据 * @param context * @return */public static Map<String,String> getUserInfo(Context context) {File file = new File(context.getFilesDir(),"info.txt");try {FileInputStream fis = new FileInputStream(file);//也可直接读取文件String result = StreamTools.readFromStream(fis);BufferedReader br = new BufferedReader(new InputStreamReader(fis));String str = br.readLine();String[] infos = str.split(":");Map<String,String> map = new HashMap<String, String>();map.put("username", infos[0]);map.put("password", infos[1]);return map;} catch(Exception e) {e.printStackTrace();return null;}}//最后可以直接调用上面的方法读取信息Map<String, String> map = getUserInfo(this);If(map!=null){Textview.setText(map.get(“username”));}
二、保存文件到SD卡
获取手机sd空间的大小:
File path = Environment.getExternalStorageDirectory();StatFs stat = new StatFs(path.getPath());long blockSize = stat.getBlockSize();long totalBlocks = stat.getBlockCount();long availableBlocks = stat.getAvailableBlocks();long totalSize = blockSize*totalBlocks;long availSize = blockSize * availableBlocks;String totalStr = Formatter.formatFileSize(this,totalSize);String availStr = Formatter.formatFileSize(this, availSize);tv.setText("总空间"+totalStr+"
"+"可用空间"+availStr);
加入写外部存储的权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>public static void save(String name ,String password) throws Exception{if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){File file = new File(Environment.getExternalStorageDirectory(),"info.txt");//也可直接写/sdcard/info.txt 先判断sd卡是否存在FileOutputStream fos = new FileOutputStream(file);String txt = name+":"+password;fos.write(txt.getBytes());fos.flush();fos.close();// 使用RandomAccessFile像文件追加内容FileOutputStream会把原有的文件内容清空//RandomAccessFile raf = new RandomAccessFile(file,"rw");//raf.seek(file.length()); 将文件指针移动到最后//raf.write(name.getBytes()+password.getBytes());//raf.close();}}
//读取文件 加入读取权限public static String read(){try {if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){File sdcardDir = Environment.getExternalStorageDirectory();FileInputStream fis = new FileInputStream(sdcardDir.getCanonicalPath() + "info.txt");BufferedReader br = new BufferedReader(new InputStreamReader(fis));StringBuilder sb = new StringBuilder("");String line = null;while ((line = br.readLine())!= null){sb.append(line);}return sb.toString();}} catch (Exception e) {e.printStackTrace();}return null;}
三、Sharedpreferences的使用
SharedPreference是开发中常用的一种存储方式,主要存储一些系统不变的参数如是否是第一次进入应用程序等,通过键值对的方式进行存储
可以存储的类型:booleans, floats, ints, longs,strings.
getSharedPreferences() - 存储多个参数
getPreferences() - 仅存储一个参数并且不需要指定名字(key)
写入的步骤:
SharedPreferences调用edit()得到一个Editor对象
使用 putBoolean() and putString()添加值
提交事务完成存储
读取时:只需要调用SharedPreferences的getBoolean() and getString()
下面是示例代码:
public class MySharedPreference {private Context context;private SharedPreferences sp ;private Editor edit;public MySharedPreference(Context context){this.context = context;}public boolean saveMessage(String name,String pwd){boolean flag = false; sp = context.getSharedPreferences("userInfo",Context.MODE_PRIVATE); //MODE定义了访问的权限现在是本应用可以访问edit = sp.edit();edit.putString("name", name);edit.putString("pwd", pwd);flag = edit.commit();//提交事务将数据持久化到存储器中return flag;}public Map<String,Object> getMessage(){Map<String,Object> map = new HashMap<String, Object>();sp = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);String name = sp.getString("name", "");String pwd = sp.getString("pwd", "");map.put("name", name);map.put("pwd",pwd);return map;}}