全部博文(131)
分类: Java
2011-11-15 16:02:11
可以知道,在默认情况下文件是不能在不同的程序间共享的。
同样,生成的文件在data/data中对应的目录下可以找到
package lau.com;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.TextView;
public class AndroidPractice extends Activity {
/** Called when the activity is first created. */
private SharedPreferences mSharedPreferences = null;
boolean b;
private TextView mTextView = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSharedPreferences = getPreferences(Activity.MODE_PRIVATE);
mTextView = (TextView)findViewById(R.id.tv);
// 读取文件数据.
load();
if(b) {
mTextView.setText("true");
} else {
mTextView.setText("false");
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(keyCode == KeyEvent.KEYCODE_BACK) {
SharedPreferences uiState = getPreferences(0);
//保存数据
save();
this.finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
switch(keyCode) {
case KeyEvent.KEYCODE_DPAD_UP:
mTextView.setText("true");
b = true;
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
mTextView.setText("false");
b = false;
break;
default:
break;
}
return super.onKeyUp(keyCode, event);
}
void load() {
Properties properties = new Properties();
try {
FileInputStream stream = this.openFileInput("settingfile.cfg");
properties.load(stream);
} catch (FileNotFoundException e) {
// TODO: handle exception
return;
} catch (IOException e) {
return;
}
b = Boolean.valueOf(properties.get("bool").toString());
}
boolean save() {
Properties properties = new Properties();
properties.put("bool", String.valueOf(b));
try {
FileOutputStream stream = this.openFileOutput("settingfile.cfg", Context.MODE_WORLD_WRITEABLE);
properties.store(stream, "");
} catch (FileNotFoundException e) {
// TODO: handle exception
return false;
} catch (IOException e) {
return false;
}
return true;
}
}