Android实验篇2_文件存取以及Sharedpreferences存取

一、实现效果

主要是IO和Sharedpreferences的数据持久化,对于后者xml更为方便易实现

对于传统IO,不仅需要各种 抓异常,还要确定找出文件存储的位置,很费力

Sharedpreferences的存取大致实现了,传统IO的还存在些问题,可能是虚拟机的问题,大致逻辑基本跑通了

效果图

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

二、代码

  • 清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="henu.soft.demo2_ioandsharedpreferences">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Demo2_IOAndSharedpreferences">
<!--        清单声明-->
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

<!--        Io页面-->
        <activity android:name=".MyIoActivity"/>




<!--        Sharedpreferences页面-->
        <activity android:name=".MySharedpreferenceActivity">
            <intent-filter>
                <action android:name="sp" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>
  • MainActivity.java
package henu.soft.demo2_ioandsharedpreferences;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 监听按钮
        findViewById(R.id.btn_io).setOnClickListener(this);
        findViewById(R.id.btn_sp).setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
    
    
        switch (v.getId()){
    
    
            case R.id.btn_io:
                // 显示意图启动
                Intent intent = new Intent(MainActivity.this,MyIoActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_sp:
                // 隐式意图 启动
                Intent intent1 = new Intent();
                intent1.setAction("sp");
                startActivity(intent1);
                break;

        }

    }
}
  • activity_main.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"
    tools:context=".MainActivity"
    android:orientation="vertical"
    android:background="@color/purple_200"
    >

    <Button
        android:id="@+id/btn_io"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="IO内、外部文件存储"
        android:textSize="20sp"
        android:layout_gravity="center_horizontal"
        />

    <Button
        android:id="@+id/btn_sp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="sharedpreferences文件存储"
        android:textSize="20sp"
        android:layout_gravity="center_horizontal"
        />



</LinearLayout>
  • MyIoActivity.java
package henu.soft.demo2_ioandsharedpreferences;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class MyIoActivity extends AppCompatActivity implements View.OnClickListener {
    
    

    String filename;
    String content;

    String myFilename = "";
    String myContent = "";


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
    
    

        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_io);

        // 监听按钮
        findViewById(R.id.btn_saveInternal).setOnClickListener(this);
        findViewById(R.id.btn_saveExternal).setOnClickListener(this);
        findViewById(R.id.btn_getInternal).setOnClickListener(this);
        findViewById(R.id.btn_getExternal).setOnClickListener(this);



    }

    @Override
    public void onClick(View v) {
    
    
        switch (v.getId()){
    
    
            // 存
            case R.id.btn_saveInternal:


                EditText editText = findViewById(R.id.et_filename);
                filename = editText.getText().toString()+".txt";
                EditText editText1 = findViewById(R.id.et_content);
                content = editText1.getText().toString();
                System.out.println("debug===> "+ filename);
                System.out.println("debug===> "+ content);
                if(filename.isEmpty() || content.isEmpty()){
    
    
                    Toast.makeText(this, "数据名称和内容不能为空!请重新输入~by:xiaosi", Toast.LENGTH_LONG).show();
                    return;
                }

                try {
    
    
                    MyInternalSave(filename,content);
                    Toast.makeText(this, "内部存储文件存储成功!", Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }


                break;
            case R.id.btn_saveExternal:
                if("".equals(filename) || "".equals(content)){
    
    
                    Toast.makeText(this, "数据名称和内容不能为空!请重新输入~by:xiaosi", Toast.LENGTH_LONG).show();
                }
                EditText editText2 = findViewById(R.id.et_filename);
                filename = editText2.getText().toString()+".txt";
                EditText editText3 = findViewById(R.id.et_content);
                content = editText3.getText().toString();


                try {
    
    
                    MyExternalSave(filename,content);
                    Toast.makeText(this, "外部存储文件获取成功!", Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }

                break;

                // 取
            case R.id.btn_getInternal:
                try {
    
    
                    MyInternalGet(filename);
                   TextView tv =  findViewById(R.id.tv_showInternalContent);
                   tv.setText("文件路径:" + myFilename +" ,内容:" +  myContent);
                    Toast.makeText(this, "内部存储文件获取成功!", Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                    Toast.makeText(this, "内部存储文件获取失败!", Toast.LENGTH_SHORT).show();
                }

                break;

            case R.id.btn_getExternal:
                try {
    
    
                    MyInternalGet(filename);
                    TextView tv =  findViewById(R.id.tv_showExternalContent);
                    tv.setText("文件路径:" + myFilename +" ,内容:" +  myContent);
                    Toast.makeText(this, "外部存储文件获取成功!", Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                    Toast.makeText(this, "外部存储文件获取失败!", Toast.LENGTH_SHORT).show();
                }

                break;

        }

    }

    /**
     * 1. 封装Internal方法
     * @param filename
     * @param content
     * @throws IOException
     */

    public void MyInternalSave(String filename,String content) throws IOException {
    
    
        FileOutputStream fos = null;

        try {
    
    
            fos = openFileOutput(filename,MODE_PRIVATE);
            fos.write(content.getBytes());
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            fos.close();
        }


    }

    /**
     * 2. 封装External方法
     * @param filename
     * @param content
     * @throws IOException
     */

    public void MyExternalSave(String filename,String content) throws IOException {
    
    

        File file = null;
        // 获取外部存储的状态
        String state = Environment.getExternalStorageState();

        if(state.equals(Environment.MEDIA_MOUNTED)){
    
    
            File SDPath = Environment.getDownloadCacheDirectory();
            file = new File(SDPath,filename);

        }else{
    
    
            Toast.makeText(this, "外部存储不可用!", Toast.LENGTH_LONG).show();
            return;
        }
        FileOutputStream fos = null;

        try {
    
    
            fos = new FileOutputStream(file);
            fos.write(content.getBytes());
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            fos.close();
        }


    }


    /**
     * 3. 封装获取Internal方法
     * @param filename
     * @throws IOException
     */
    public void MyInternalGet(String filename) throws IOException {
    
    

        FileInputStream fis = null;

        try {
    
    
            fis = openFileInput(filename);

            byte[] buffers = new byte[fis.available()];
            fis.read(buffers);
            myFilename = filename;
            myContent = new String(buffers);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            fis.close();

        }

    }


    /**
     * 4. 封装获取Externale方法
     * @param filename
     * @throws IOException
     */
    public void MyExternalGet(String filename) throws IOException {
    
    



        // 获取外部存储的状态
        String state = Environment.getExternalStorageState();
        File file = null;

        if(state.equals(Environment.MEDIA_MOUNTED)){
    
    
            File SDPath = Environment.getDownloadCacheDirectory();
            file = new File(SDPath,filename);

        }else{
    
    
            Toast.makeText(this, "外部存储不可用!", Toast.LENGTH_LONG).show();
            return;
        }
        FileInputStream fis = null;
        BufferedReader br = null;

        try {
    
    
            fis = new FileInputStream(file);
            br = new BufferedReader(new InputStreamReader(fis));
            myContent = br.readLine();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            br.close();
            fis.close();
        }


    }



}

  • layout_io.xml
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >


    <!--    第一行,文件名称-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView

            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"

            android:text="文件名称:"
            android:textSize="20sp"
            />

        <EditText
            android:id="@+id/et_filename"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="请输入存入的文件名称"/>

    </LinearLayout>

    <!--    第二行,文件内容-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView

            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"

            android:text="文件名称:"
            android:textSize="20sp"
            />

        <EditText
            android:id="@+id/et_content"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="请输入存入的内容"/>

    </LinearLayout>

    <!--    第三行,存入按钮-->

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

        <Button
            android:id="@+id/btn_saveInternal"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"
            android:text="存入internal文件"
            />

        <Button
            android:id="@+id/btn_saveExternal"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"
            android:text="存入external文件"
            />

    </LinearLayout>

<!--    第四行,显示Internal文件内容-->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView

            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"

            android:text="Internal文件内容:"
            android:textSize="20sp"
            />

        <TextView
            android:id="@+id/tv_showInternalContent"
            android:layout_width="0dp"
            android:layout_height="50sp"
            android:layout_weight="1"


            android:textSize="20sp"
            />

    </LinearLayout>

<!--    第五行,显示External文件内容-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView

            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"

            android:text="External文件内容:"
            android:textSize="20sp"
            />

        <TextView
            android:id="@+id/tv_showExternalContent"
            android:layout_width="0dp"
            android:layout_height="50sp"
            android:layout_weight="1"


            android:textSize="20sp"
            />

    </LinearLayout>


<!--    第六行,取出按钮-->

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

        <Button
            android:id="@+id/btn_getInternal"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"
            android:text="取出显示internal文件"
            />

        <Button
            android:id="@+id/btn_getExternal"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"
            android:text="取出显示external文件"
            />

    </LinearLayout>


</LinearLayout>
  • MySharedpreferenceActivity.java
package henu.soft.demo2_ioandsharedpreferences;



import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;

public class MySharedpreferenceActivity extends AppCompatActivity implements View.OnClickListener {
    
    


    String content = "";
    String myContent = "";

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

        // 监听按钮
        findViewById(R.id.btn_saveContent).setOnClickListener(this);
        findViewById(R.id.btn_showContent).setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
    
    
        switch (v.getId()) {
    
    
            // 存
            case R.id.btn_saveContent:
                EditText editText = findViewById(R.id.et_input);
                content = editText.getText().toString();
                if ("".equals(content)) {
    
    
                    Toast.makeText(this, "数据内容不能为空!请重新输入~by:xiaosi", Toast.LENGTH_LONG).show();
                }
                saveContent(content);
                Toast.makeText(this, "数据存入成功!~by:xiaosi", Toast.LENGTH_LONG).show();
                break;
            // 取
            case R.id.btn_showContent:
                TextView tv = findViewById(R.id.tv_result);
                showContent(content);
                if(myContent.isEmpty()){
    
    
                    Toast.makeText(this, "获取了个寂寞~请重新保存再获取~by:xiaosi", Toast.LENGTH_LONG).show();
                }
                tv.setText(myContent);


                Toast.makeText(this, "数据获取成功!~by:xiaosi", Toast.LENGTH_LONG).show();
                break;
        }
    }

    /**
     * 1. 存储数据到SharedPreferences
     * @param content
     */

    public void saveContent(String content){
    
    
        SharedPreferences sp = getSharedPreferences("data",MODE_PRIVATE);

        // 获取编辑器对象
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(content,content);
        edit.commit();

    }

    /**
     * 1. 读取SharedPreferences
     * @param content
     */

    public void showContent(String content){
    
    
        SharedPreferences sp = getSharedPreferences("data",MODE_PRIVATE);

        myContent = sp.getString(content, "");

    }
}


  • layout_sharedpreferences.xml
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >


    <!--    第一行,存入-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/et_input"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"


            android:hint="请输入要保存的内容"
            />

        <Button
            android:id="@+id/btn_saveContent"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"
            android:text="保存到SharedPreference"
            />

    </LinearLayout>

    <!--    第二行,取出-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/tv_result"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"

            />

        <Button
            android:id="@+id/btn_showContent"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="10dp"
            android:text="从SharedPreference取出来"
            />

    </LinearLayout>

</LinearLayout>

猜你喜欢

转载自blog.csdn.net/qq_24654501/article/details/115432629