Android文件存储学习

一、将数据存储到文件中

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();
				}
			}
		}

	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值