SharedPrefences ,openFileOputStrean,openFileInputStream 总结

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();


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值