android Properties的使用

 Android 下面Properties可用来保存程序的一些配置,其简单用法如下

public class MainActivity extends Activity {

	Button btnInput=null;
	Button btnRead=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mylayout);
		btnInput=(Button)findViewById(id.btnInput);
		btnInput.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//首先创建 Properties
				Properties pro=new Properties();
				pro.put("name", "test");
				SetProperties(pro);
			}
		});
		
		btnRead=(Button)findViewById(id.bntRead);
		btnRead.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//读取
				Properties pro=GetProperties();
				Toast.makeText(MainActivity.this,pro.getProperty("name"), Toast.LENGTH_SHORT).show();
				
			}
		});
	}
	/**
	 * 获取Properties
	 * @return
	 */
	private Properties GetProperties(){
		Properties pro=new Properties();
		FileInputStream stream=null;
		File file=this.getDir("Config", Context.MODE_PRIVATE);
		try {
			stream=new FileInputStream(file.getPath()+File.separator+"config");
			pro.load(stream);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				stream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return pro;
	}
	/**
	 * 设置Properties
	 * @param pro
	 */
	private void SetProperties(Properties pro){
		FileOutputStream stream=null;
		File dir=this.getDir("Config", Context.MODE_PRIVATE);//获得路径为data/data/包名/app_+传入的name  这里为app_config
		try {
			File  file=new File(dir,"config");//在上面的路径下创建config文件
			stream=new FileOutputStream(file);
			pro.store(stream,"");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值