与前面的文章[url]http://leequer.iteye.com/blog/607079[/url]android的数据存储和访问 附源码这篇文章相比,添加了文件的读取功能和代码的优化
package cn.lee.data;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import cn.lee.Manager.DataManager;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AboutDateActivity extends Activity {
private EditText fileNameEditText;
private EditText fileContentEditText;
private EditText readfileContentEditText;
private Button button;
private Button readButton;
private static final String TAGSTRING = "AboutDateActivity";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) this.findViewById(R.id.button);
readButton = (Button) this.findViewById(R.id.readButton);
fileNameEditText = (EditText) this.findViewById(R.id.fileName);
fileContentEditText = (EditText) this.findViewById(R.id.fileContent);
readfileContentEditText = (EditText) this.findViewById(R.id.readfileContent);
// 读取
readButton.setOnClickListener(onClickListener);
// 保存
button.setOnClickListener(onClickListener);
}
/**
* 由于这个内部实现类是一个接口的实例 所以这里把他提取出来 作为一个成员变量 2010-04-18
*/
private View.OnClickListener onClickListener = new View.OnClickListener() {
/**
* 由于button的父类是view 所以这里的onclick的参数传来的view v就可以找到这个button
*/
public void onClick(View v) {
Button button = (Button) v;// 将父类view强转成子类button
int info = R.string.sus;
String fileNameString = fileNameEditText.getText().toString();
if ("".equals(fileNameString)) {
info = R.string.filenamenotnull;
} else {
FileOutputStream fileOutputStream = null;
FileInputStream fileInputStream = null;
try {
switch (button.getId()) {
case R.id.button: {// 保存
String fileContentString = fileContentEditText.getText().toString();
fileOutputStream = AboutDateActivity.this
.openFileOutput(fileNameString,
Context.MODE_PRIVATE);
DataManager.saveDate(fileOutputStream,
fileContentString);
break;
}
case R.id.readButton: {
fileInputStream = null;
fileInputStream = AboutDateActivity.this
.openFileInput(fileNameString);
String contentString = DataManager
.readDate(fileInputStream);
readfileContentEditText.setText(contentString);
break;
}
default:
break;
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.i(TAGSTRING, e.toString());
info = R.string.infor;
} finally {
try {
if(fileOutputStream!=null)
{
fileOutputStream.close();
}
if(fileInputStream !=null)
{
fileInputStream.close();
}
} catch (IOException e) {
Log.i(TAGSTRING, e.toString());
info = R.string.infor;
}
}
}
Toast.makeText(AboutDateActivity.this, info, 1).show();
}
};
}