SharedPrefences ,openFileOputStrean,openFileInputStream 总结

来源:互联网 发布:淘宝上可爱文具店 编辑:程序博客网 时间:2024/05/16 00:53
preferences = getSharedPreferences("crazyt", MODE_PRIVATE);
editor = preferences.edit();
read = (Button) this.findViewById(R.id.button1);
write = (Button) this.findViewById(R.id.button2);
read.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String time = preferences.getString("time", null);
int randNum = preferences.getInt("random", 0);
String result = time == null ? "暂未写入" : "写入时间为:" + time
+ "\n生成随机数" + randNum;
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT)
.show();
}
});
write.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
editor.putString("time", sdf.format(new Date()));
editor.putInt("random", (int) (Math.random() * 1000));
editor.commit();


}
});
Context umContext = null;
// 读其他应用的文件 context_ignore_security
try {
umContext = createPackageContext("org.crazy.io",
Context.CONTEXT_IGNORE_SECURITY);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
SharedPreferences preferences = umContext.getSharedPreferences("count",
Context.MODE_WORLD_READABLE);


int count = preferences.getInt("count", 0);
tView = (TextView) this.findViewById(R.id.textView1);
tView.setText("应用被点击了" + count);
// openFileOutStream 、openFileInputStream文件读写
et1 = (EditText) this.findViewById(R.id.editText1);
et2 = (EditText) this.findViewById(R.id.editText2);
openOut.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
write(et1.getText().toString());
et1.setText("");
}
});
openInput.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
et2.setText(read());
}
});
}
//读取刚才用户保存的内容
/*ByteArrayOutputStream extends OutputStream*/
private String read()   { 
try {
FileInputStream  fis=openFileInput(FILE_NAME);
byte[] bytes=new byte[1024];
ByteArrayOutputStream  bais=new ByteArrayOutputStream();
while(fis.read()!=-1){
bais.write(bytes,0,bytes.length);
}
fis.close();
bais.close();
String content=new String(bais.toByteArray());
et1.setText(content);
}catch (Exception e) { 
e.printStackTrace();

return null;
}
    
private void write(String content) {
try {
FileOutputStream  fos=openFileOutput(FILE_NAME, Context.MODE_APPEND);
fos.write(content.getBytes());
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(this, "写入成功", Toast.LENGTH_SHORT).show();


}
原创粉丝点击