プロジェクトディレクトリ:
MainActivity
package com.example.demo82;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
EditText et;
Button btn1,btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et=findViewById(R.id.editText);
btn1=findViewById(R.id.button);
btn2=findViewById(R.id.button2);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int se=v.getId();
switch(se){
case R.id.button:
String str=et.getText().toString();
try{
FileOutputStream out=openFileOutput("text", Context.MODE_APPEND);
out.write(str.getBytes());
out.close();
Toast.makeText(this, "信息保存成功!", Toast.LENGTH_SHORT).show();
}
catch (Exception e){
e.printStackTrace();
}
break;
case R.id.button2:
String mess="";
try{
FileInputStream in=openFileInput("text");
byte[] buffer=new byte[in.available()];
in.read(buffer);
mess=new String(buffer);
in.close();
}
catch(Exception e){
e.printStackTrace();
}
Toast.makeText(this,mess, Toast.LENGTH_SHORT).show();
break;
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:hint="请输入保存文本"
android:text="" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="保存" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="读取" />
</LinearLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>