通过Android的openFileInput、openFileOutput来获取一个文件输入输出流,从而实现写入/读取文件。主界面只有一个EditText,其中的内容在活动销毁时会自动保存到文件。
主布局文件:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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/edittext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="这里的内容会自动保存"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
主活动类:
public class MainActivity extends AppCompatActivity {
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.edittext);
String data = load();
if (!TextUtils.isEmpty(data)) {//这里会同时判断两种空值状态 null 和 ""
editText.setText(data);
editText.setSelection(data.length());//设置光标位置到输入框的最后
}
}
// 从文件里引导数据
private String load() {
FileInputStream fileInputStream = null;
BufferedReader bufferedReader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
fileInputStream = openFileInput("data.txt");
bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return stringBuilder.toString();
}
@Override
protected void onDestroy() {
super.onDestroy();
save();
}
private void save() {
String data = editText.getText().toString();
FileOutputStream fileOutputStream;
BufferedWriter bufferedWriter = null;
try {
fileOutputStream = openFileOutput("data.txt", Context.MODE_PRIVATE);
bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
bufferedWriter.write(data);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedWriter != null) {
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
运行截图: