一、将数据存储到文件中
Context类中提供了一个openFileOutput()方法,可以将数据存储到指定的文件中。该方法接收两个参数,第一个参数是文件名,在文件创建的时候使用这个名字(默认存储到/data/data/package name/files/目录下),第二个参数是文件的操作模式,主要有MODE_PRIVATE和MODE_APPEND.
在activity_main.xml中的代码如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<EditText android:id="@+id/edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="type sth. here!"
/>
</RelativeLayout>
MainActivity代码:
public class MainActivity extends Activity {
private EditText et;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.edit);
}
@Override
protected void onDestroy() {
super.onDestroy();
String inputText = et.getText().toString();
save(inputText);
}
private void save(String inputText) {
FileOutputStream fs = null;
BufferedWriter bw = null;
try {
fs = openFileOutput("data_cat", Context.MODE_PRIVATE);
bw = new BufferedWriter(new OutputStreamWriter(fs));
bw.write(inputText);
} catch (Exception e) {
// TODO: handle exception
} finally {
{
try {
if (bw != null)
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}