android中的数据存储(1)
(1)数据存储之Shared Preferences:用来存储“key-value”格式的数据
public static final String PREFS_NAME = "MyPrefsFile";
Boolean mbMusic = false;
//保存到preferences:
SharedPreferences settings = getPreferences(0);//或者SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
settings.edit()
.putBoolean("bMusic", mbMusic)
.commit();
//读取preferences
SharedPreferences settings = getPreferences(0);//或者SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
settings.getBoolean("bMusic", false);
(2)数据存储之Files
public class ReadWrite extends Activity {
private static final String str = "文件输入输出练习";
/** Called when the activity is first created. */
TextView textView ;
String fileName = "aa.txt";
String result;
public static final String PREFS_NAME = "MyPrefsFile";
Boolean mbMusic = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.textView);
WirteData(fileName,str);//写数据
result=ReadData("aa.txt");//读取数据
textView.setText(result);
}
private String ReadData(String fileName) {
// TODO Auto-generated method stub
String result = "";
try {
FileInputStream fin=openFileInput(fileName);
int length = fin.available();
byte[] buffer = new byte[length];
fin.read(buffer);
result = EncodingUtils.getString(buffer, "UTF-8");
fin.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
private void WirteData(String fileName, String str) {
// TODO Auto-generated method stub
try {
FileOutputStream fout=openFileOutput(fileName, MODE_PRIVATE);
byte [] buffer = str.getBytes();
fout.write(buffer);
fout.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}