数据操作工具类——文件操作类

public class FileHelper {

private Context mContext;

public FileHelper() {
}

public FileHelper(Context mContext) {
super();
this.mContext = mContext;
}

/*
* 这里定义的是一个文件保存的方法,写入到文件中,所以是输出流
* */
public void save(String filename, String filecontent) throws Exception {
//这里我们使用私有模式,创建出来的文件只能被本应用访问,还会覆盖原文件哦
FileOutputStream output = mContext.openFileOutput(filename, Context.MODE_PRIVATE);
output.write(filecontent.getBytes()); //将String字符串以字节流的形式写入到输出流中
output.close(); //关闭输出流
}


/*
* 这里定义的是文件读取的方法
* */
public String read(String filename) throws IOException {
//打开文件输入流
FileInputStream input = mContext.openFileInput(filename);
byte[] temp = new byte[1024];
StringBuilder sb = new StringBuilder("");
int len = 0;
//读取文件内容:
while ((len = input.read(temp)) > 0) {
sb.append(new String(temp, 0, len));
}
//关闭输入流
input.close();
return sb.toString();
}

}

 

最后是MainActivity.java,我们在这里完成相关操作:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private EditText editname;
private EditText editdetail;
private Button btnsave;
private Button btnclean;
private Button btnread;
private Context mContext;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = getApplicationContext();
bindViews();
}


private void bindViews() {
editdetail = (EditText) findViewById(R.id.editdetail);
editname = (EditText) findViewById(R.id.editname);
btnclean = (Button) findViewById(R.id.btnclean);
btnsave = (Button) findViewById(R.id.btnsave);
btnread = (Button) findViewById(R.id.btnread);

btnclean.setOnClickListener(this);
btnsave.setOnClickListener(this);
btnread.setOnClickListener(this);
}


@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnclean:
editdetail.setText("");
editname.setText("");
break;
case R.id.btnsave:
FileHelper fHelper = new FileHelper(mContext);
String filename = editname.getText().toString();
String filedetail = editdetail.getText().toString();
try {
fHelper.save(filename, filedetail);
Toast.makeText(getApplicationContext(), "数据写入成功", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "数据写入失败", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btnread:
String detail = "";
FileHelper fHelper2 = new FileHelper(getApplicationContext());
try {
String fname = editname.getText().toString();
detail = fHelper2.read(fname);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), detail, Toast.LENGTH_SHORT).show();
break;
}
}
}

posted @ 2017-09-19 17:55  鹏达君  阅读(222)  评论(0编辑  收藏  举报