Android使用输入/输出流存储文件

一、简述

  • 描述:使用 FileOutputStream 将新建文件存储到内部存储器和SD存储器当中,并使用 FileInputStream 读取文件内容。

  • 难度:初级

  • 知识点:权限申请、FileOutputStream、FileInputStream

  • 使用输入/输出流存储文件(内部存储andSD存储)

二、注册权限

在这里插入图片描述

    <!--  向外部存储器写入数据权限  -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

三、编写操作类

1、获取权限

判断当前软件是否有写入数据权限(tool -> FileStorage.java)

	private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
        /**
     * 获取权限
     * @param activity
     */
    public static void verifyStoragePermissions(Activity activity) {
        // 当前是否有写入的权限
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // 没有权限,提醒授权
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    1);
        }
    }
2、内部存储器读写
	/**
     * 写入内部存储器
     * @param activity
     * @param fileName
     * @param text
     */
    public static void saveFile(Activity activity, String fileName, String text) {
        try {
            FileOutputStream out = activity.openFileOutput(fileName + ".txt", activity.MODE_PRIVATE);
            out.write(text.getBytes());
            out.flush();
            out.close();
            Toast.makeText(activity, "内部文件保存成功!", Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取内部存储器
     * @param activity
     * @param fileName
     * @return
     */
    public static String readFile(Activity activity, String fileName) {
        String x = "";
        byte[] buffer = new byte[1024];
        FileInputStream in = null;
        try {
            in = activity.openFileInput(fileName + ".txt");
            int bytes = in.read(buffer);
            x = new String(buffer, 0, bytes);
        } catch (FileNotFoundException e) {
            x = "文件不存在!";
        } catch (IOException e) {
            x = "IO流错误!";
        }
        return x;
    }
3、SD卡读写
    /**
     * 写入SD卡
     * @param activity
     * @param fileName
     * @param text
     */
    public static void saveSDFile(Activity activity, String fileName, String text) {
        // 判断SD卡是否有读写权限
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File p = Environment.getExternalStorageDirectory();
            String strPath = p.getAbsolutePath();
            File q = new File(strPath + "/" + fileName + ".txt");
            try {
                FileOutputStream out = new FileOutputStream(q);
                out.write(text.getBytes());
                out.flush();
                out.close();
                Toast.makeText(activity, "SD文件保存成功!", Toast.LENGTH_SHORT).show();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Log.i("file", "文件未找到!");
            } catch (IOException e) {
                e.printStackTrace();
                Log.i("file", "其他异常!");
            }
        } else {
            // 没有 就再次提醒
            verifyStoragePermissions(activity);
            Log.i("file", "sd卡不可访问!");
        }
    }

    /**
     * 读取SD卡
     * @param activity
     * @param fileName
     */
    public static String readSDFile(Activity activity, String fileName) {
        String x = "";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File p = Environment.getExternalStorageDirectory();
            String strPath = p.getAbsolutePath();
            File q = new File(strPath, fileName + ".txt");
            try {
                FileInputStream put = new FileInputStream(q);
                byte[] buffer = new byte[1024];
                int bytes = put.read(buffer);
                x = new String(buffer, 0, bytes);
            } catch (FileNotFoundException e) {
                x = "文件不存在!";
            } catch (IOException e) {
                x = "IO流错误!";
            }
        } else {
            verifyStoragePermissions(activity);
        }
        return x;
    }

四、XXActivity

1、UI界面
  • 展示
    在这里插入图片描述
  • 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="#F0F0F0"
    android:paddingTop="50dp">

    <EditText
        android:id="@+id/fileName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#FFFFFF"
        android:padding="10dp"
        android:layout_margin="10dp"
        android:hint="创建的文件名"/>

    <EditText
        android:id="@+id/fileText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_margin="10dp"
        android:background="#FFFFFF"
        android:padding="10dp"
        android:hint="添加内容"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:gravity="center">

        <Button
            android:id="@+id/setFile"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:background="@drawable/shape"
            android:text="内部存储"/>

        <Button
            android:id="@+id/getFile"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_marginLeft="10dp"
            android:background="@drawable/shape"
            android:text="读取内容"/>

        <Button
            android:id="@+id/setSDFile"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_marginLeft="10dp"
            android:background="@drawable/shape"
            android:text="SD存储"/>

        <Button
            android:id="@+id/getSDFile"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_marginLeft="10dp"
            android:background="@drawable/shape"
            android:text="读取SD内容"/>

    </LinearLayout>

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

        <EditText
            android:id="@+id/showText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:textSize="25dp"/>
    </LinearLayout>

</LinearLayout>
2、实现代码
  • MainActivity.java
	private Button setFile, getFile, setSDFile, getSDFile;
    private EditText fileName, fileText;
    private TextView showText;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 获取权限
        FileStorage.verifyStoragePermissions(MainActivity.this);
        // 初始化
        init();
    }

    private void init() {
        // Button
        setFile = findViewById(R.id.setFile);
        getFile = findViewById(R.id.getFile);
        setSDFile = findViewById(R.id.setSDFile);
        getSDFile = findViewById(R.id.getSDFile);
        // EditText
        fileName = findViewById(R.id.fileName);
        fileText = findViewById(R.id.fileText);
        showText = findViewById(R.id.showText);
        // 触发事件
        setFile.setOnClickListener(this);
        getFile.setOnClickListener(this);
        setSDFile.setOnClickListener(this);
        getSDFile.setOnClickListener(this);
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        String file_name = fileName.getText().toString();
        String file_text = fileText.getText().toString();
        String text = "";
        switch (v.getId()) {
            case R.id.setSDFile:
                FileStorage.saveSDFile(MainActivity.this, file_name, file_text);
                break;
            case R.id.getSDFile:
                text = FileStorage.readSDFile(MainActivity.this, file_name);
                showText.setText("结果:" + text);
                break;
            case R.id.setFile:
                FileStorage.saveFile(MainActivity.this, file_name, file_text);
                break;
            case R.id.getFile:
                text = FileStorage.readFile(MainActivity.this, file_name);
                showText.setText("结果:" + text);
                break;
        }
    }

五、源代码

Android使用输入/输出流存储文件
git地址

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云端new守夜人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值