Properties(屬性),可以把Properties繼承自Hashtable,理解成一個Hashtable ,不過唯一不同的是,Properties對應的“鍵-值”必須是字串形式的資料類型。Files 資料存放區主要是使用 Properties 配合 FileInputStream或者FileOutputStream對檔案寫入操作。
代碼
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==btnlogin.getId()){
Properties properties=new Properties();
String name=etname.getText().toString();
String pwd=etpwd.getText().toString();
try {
// 檔案建立模式:MODE_APPEND
// 如果該檔案已經存在,然後將資料寫入,而不是抹掉它現有檔案的末尾。
// 檔案建立模式:MODE_PRIVATE
// 預設模式,在那裡建立的檔案只能由應用程式調用,即為私人的
// 檔案建立模式:MODE_WORLD_READABLE
// 允許所有其他應用程式有讀取和建立檔案的許可權。
// 檔案建立模式:MODE_WORLD_WRITEABLE
// 允許所有其他應用程式具有寫入、訪問和建立的檔案許可權。
FileOutputStream out=this.openFileOutput("login.cfg",Context.MODE_PRIVATE);
properties.put("name", name);
properties.put("pwd", pwd);
try {
properties.store(out, "");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
loadInfo();
}
}
//儲存檔案
public void loadInfo(){
Properties properties=new Properties();
try {
FileInputStream in=this.openFileInput("login.cfg");
try {
properties.load(in);
String name=properties.get("name").toString()+"///";
String pwd=properties.get("pwd").toString()+"///";
this.etname.setText(name);
this.etpwd.setText(pwd);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}