今天我们来学习下文件存储。文件存储算是Android中最为基础的一种数据存储方式了。它比较适合用于存储一些简单的文本数据后二进制数据。
那么我们就先来看下Android是如何通过文件来保存数据的
将数据存储到文件中
首先,我们需要创建一个新的项目,并修改activity_main.xml文件。我就直接上代码了,毕竟挺简单的。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:hint="在这里输入内容"/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="保存" />
</LinearLayout>
代码比较简单,我们创了一个EditText和Button。EditText用于输入文本内容。Button用于实现保存数据到文件之中。等你输入完你的内容,按下保存键,这样你输入的内容就会在回收前存储到文件之中去。
然后,我们就要写主要代码了。一样的,直接上代码。
public class MainActivity extends AppCompatActivity {
private EditText edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceStat