写了两个demo,一个是使用SharedPreferences将数据存储在应用文件中并读取,另一个是使用Context的openFileOutput和openFileInput将数据存储在应用文件中并读取。
SharedPreferences以key-value键值对存储,存储地址在
data/data/yourApp'sPackage/shared_prefs/yourSharedFileName.xml
Context以文件形式存储,存储地址在
data/data/yourApp'sPackage/files/yourSharedFileName
主要涉及Activity代码如下:
class HandFile { private Context context; public HandFile(Context context) { this.context=context; } /** * 将message写到fileName中,有程序写出来,用fileOutPutStream * @param fileName * @param message */ public void writeFileData(String fileName, String message) { try{ FileOutputStream fileOutputStream = context.openFileOutput(fileName,context.MODE_PRIVATE); byte[]bytes = message.getBytes(); fileOutputStream.write(bytes); }catch (Exception e){ e.printStackTrace(); } } /** * 打开程序私有文件fileName,读入数据 * @param fileName * @return result */ public String readFileData(String fileName) { String result = ""; try{ FileInputStream fileInputStream = context.openFileInput(fileName); int length =fileInputStream.available(); byte[]buffer = new byte[length]; fileInputStream.read(buffer); result=new String(buffer); fileInputStream.close(); }catch (Exception e){ e.printStackTrace(); } return result; } }
/** * 缓存数据到程序中,格式为key-value */ public void initData(){ SharedPreferences read =getSharedPreferences("user",MODE_PRIVATE); String name=read.getString("name",""); String address=read.getString("address",""); if(name.equals("")&&address.equals("")){ Toast.makeText(this,"抱歉,SharedPreferences没有数据",Toast.LENGTH_LONG).show(); }else{ nameText.setText(name); addressText.setText(address); Toast.makeText(this,"您使用SharedPreference初始化数据",Toast.LENGTH_LONG).show(); } } public void onClick(View view) { /** * user表示要写入的xml文件名 * */ SharedPreferences.Editor editor=getSharedPreferences("user",MODE_PRIVATE).edit(); switch (view.getId()) { //显示意图Intent case R.id.saveAddress: String name=nameText.getText().toString(); String address =addressText.getText().toString(); /** * 将数据放入文件 */ editor.putString("name",name); editor.putString("address",address); editor.commit(); Toast.makeText(this,"您使用了SharedPreferences保存数据",Toast.LENGTH_LONG).show(); break; case R.id.delAddress: /** * 消除所有数据 */ editor.clear(); editor.commit(); Toast.makeText(this,"您删除了SharedPreferences中的所有数据",Toast.LENGTH_LONG).show(); break; } }
运行程序后 adb shell su获取root权限后查看文件夹详情如下:
generic_x86:/data/data/com.patech.testApp/files # tail first 大家好,这里市清华大学出版社出的一本Android类书籍。generic_x86:/data/data/com.patech.testApp/files # cd .. generic_x86:/data/data/com.patech.testApp # ls cache code_cache files shared_prefs generic_x86:/data/data/com.patech.testApp # cd shared_prefs generic_x86:/data/data/com.patech.testApp/shared_prefs # ls user.xml 127|generic_x86:/data/data/com.patech.testApp/shared_prefs # tail user.xml <?xml version='1.0' encoding='utf-8' standalone='yes' ?> <map> <string name="address">hello</string> <string name="name">hello</string> </map>