半期考试 之 文件存储

41 篇文章 2 订阅
27 篇文章 0 订阅

半期考试 之 文件存储

要求:

  • 三个EditView, 要求输入姓名,年龄,身高;
  • 点击第一个按钮,要求使用SharedPreference来存储EditView中的内容;
  • 点击第二个按钮实现跳转;
  • 第二个活动中在EditView 中输入内容,点击“保存”按钮实现通过文件的形式保存数据,点击读取按钮,下方的TextView读取文件并显示文件内容;

第一个活动:

xml :

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal|center_vertical"
            android:text="姓名:" />

        <EditText
            android:id="@+id/activity_main_et_Name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:hint="请输入姓名"
            android:inputType="textPersonName" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal|center_vertical"
            android:text="年龄:" />

        <EditText
            android:id="@+id/activity_main_et_Age"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:hint="请输入年龄"
            android:inputType="number" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center_horizontal|center_vertical"
            android:text="身高:" />

        <EditText
            android:id="@+id/activity_main_et_Height"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:hint="请输入身高"
            android:inputType="numberDecimal"
            android:text="" />
    </LinearLayout>

    <Button
        android:id="@+id/activity_main_bn_Save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="保存" />

    <Button
        android:id="@+id/activity_main_bn_Setting"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="打开SettingActivty" />

    <Button
        android:id="@+id/activity_main_bn_FileIO"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="内部文件读写" />
</LinearLayout>

java :

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    //定义布局UI组件对应的引用变量
    EditText etName;
    EditText etAge;
    EditText etHeight;
    Button bnSave;
    Button bnFileIO;
    //定义读写权限
    private int PREFERENCE_MODE = Context.MODE_PRIVATE ;
    //定义保存文件的名称
    private final String PREFERENCE_NAME = "SaveSetting";
    //定义SharedPreferences的引用变量
    SharedPreferences sp;
    SharedPreferences.Editor spEditor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //关联布局文件中的UI组件
        etName=findViewById(R.id.activity_main_et_Name);
        etAge=findViewById(R.id.activity_main_et_Age);
        etHeight=findViewById(R.id.activity_main_et_Height);

        bnSave=findViewById(R.id.activity_main_bn_Save);
        bnSave.setOnClickListener(this);
        
        bnFileIO=findViewById(R.id.activity_main_bn_FileIO);
        bnFileIO.setOnClickListener(this);

        //实例化SharedPreferences对象
        sp=getSharedPreferences(PREFERENCE_NAME,PREFERENCE_MODE);
        spEditor=sp.edit();
        //初始化显示数据
        getData();
    }

    //读出数据
    private void getData(){
        String Name=sp.getString("Name","");
        int Age=sp.getInt("Age",0);
        float Height=sp.getFloat("Height",0);

        etName.setText(Name);
        etAge.setText(""+Age);
        etHeight.setText(""+Height);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.activity_main_bn_Save:
                //写入数据
                //实例化得到一个SharedPreferences.Editor对象
                //使用SharedPreferences.Editor对象的putXXX方法将输入写入到对应的键中
                spEditor.putString("Name",etName.getText().toString());
                spEditor.putInt("Age",Integer.parseInt(etAge.getText().toString()));
                spEditor.putFloat("Height",Float.parseFloat(etHeight.getText().toString()));
                //提交修改
                spEditor.commit();
                Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();
                break;
            case R.id.activity_main_bn_FileIO:
                Intent intent2=new Intent(this,FileIOActivity.class);
                startActivity(intent2);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        spEditor.commit();
    }
}

第二个活动:

xml :

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/activity_file_io_et_Text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="请输入保存的内容"
        android:inputType="textPersonName" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

     
        <Button
            android:id="@+id/activity_file_io_bn_Write"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="保存" />

        <Button
            android:id="@+id/activity_file_io_bn_Read"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="读取" />

    </LinearLayout>


    <TextView
        android:id="@+id/activity_file_io_tv_Text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal|center_vertical" />
</LinearLayout>

java :

public class FileIOActivity extends AppCompatActivity implements View.OnClickListener {

    //定义UI组件的引用变量
    EditText etText;
    TextView tvText;
    Button bnWrite;
    Button bnRead;

    private  final String FILE_NAME="fanxk.dat";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_io);

        etText=findViewById(R.id.activity_file_io_et_Text);
        tvText=findViewById(R.id.activity_file_io_tv_Text);
        bnWrite=findViewById(R.id.activity_file_io_bn_Write);
        bnRead=findViewById(R.id.activity_file_io_bn_Read);

        bnWrite.setOnClickListener(this);
        bnRead.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.activity_file_io_bn_Write:
                writeData();
                break;
            case R.id.activity_file_io_bn_Read:
                readData();
                break;
        }
    }

    private void writeData(){
        //定义FileOutputStream的引用变量fos
        FileOutputStream fos=null;
        try {
                fos = openFileOutput(FILE_NAME,Context.MODE_PRIVATE);
            }
            //获取文本输入框的值
            String text = etText.getText().toString();
            //将值写入到fos对应的文件中
            fos.write(text.getBytes());
        } catch (FileNotFoundException e) {
            Toast.makeText(this,"未找到对应文件",Toast.LENGTH_SHORT).show();
        }
        catch (IOException e) {
            Toast.makeText(this,"写文件失败:"+e.getMessage(),Toast.LENGTH_SHORT).show();
        }
        finally{
            if (fos != null){
                try {
                    fos.flush();
                    fos.close();
                } catch (IOException e) {
                    Toast.makeText(this,"写文件失败:"+e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
    private void readData(){
        //定义FileInputStream的引用变量fis
        FileInputStream fis = null;
        try {
            //通过openFileInput方法获取一个fis实例
            fis = openFileInput(FILE_NAME);
            //判断文件是否有内容
            if (fis.available() == 0){
                return;
            }
            //定义一个二进制数组接收文件内容,通过fis.available()得到数组的大小
            byte[] readBytes = new byte[fis.available()];
            //循环读取文件内容
            while(fis.read(readBytes) != -1){
            }
            //将二进制数组转换为字符串
            String text = new String(readBytes);
            //将字符串输出到TextView
            tvText.setText(text);
            //关闭输入流对象
            fis.close();
        } catch (FileNotFoundException e) {
            Toast.makeText(this,"未找到对应文件",Toast.LENGTH_SHORT).show();
        }
        catch (IOException e) {
            Toast.makeText(this,"读文件失败:"+e.getMessage(),Toast.LENGTH_SHORT).show();
        }
    }
}

运行效果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值