Android基础篇-五大储存方式之文件存储

效果图:
这里写图片描述
有java基础的读者肯定是一目十行的,Android的文件存储就是java的字符流,字节流写入读取File

具体代码:

首先在manifest中声明权限

    <!-- 判断是否存在文件系统SD卡 -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <!-- 允许当前应用程序读取SD卡文件 -->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <!-- 允许当前程序向SD卡写入数据 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

activity_main:

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

    <EditText
        android:id="@+id/rt_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入内容" />

    <TextView
        android:id="@+id/tv_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#ff0000"
        android:textSize="22sp" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="btn_write"
        android:text="字符流写入" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="btn_byte"
        android:text="字节流写入" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="btn_byte2"
        android:text="字节流2写入" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="btn_read"
        android:text="读取字符流" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="btn_read_byte"
        android:text="读取字节流" />

</LinearLayout>

MainActivity:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    private EditText rt_text;
    private TextView tv_text;
    private File file2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rt_text = (EditText) findViewById(R.id.rt_text);
        tv_text = (TextView) findViewById(R.id.tv_text);
        //得到SD卡路径
        // Storage/SdCard
        File file = Environment.getExternalStorageDirectory();
        // Storage/Scard/text.txt
        file2 = new File(file, "text.txt");
    }

    public void btn_write(View v) {
        write_char();
    }
    public void btn_byte(View v) {
		write_byte2();
    }
    public void btn_byte2(View v) {
		write_byte();
    }
    public void btn_read(View v) {
        read_char();
    }
    public void btn_read_byte(View v) {
        read_byte();
    }


    // 字符流写入SD卡
    public void write_char() {
        //得到SD卡的状态
        String state = Environment.getExternalStorageState();
        /**
         * 只有在SD卡状态为MEDIA_MOUNTED时
         * Storage/sdcard目录才是可读可写,并且可以创建目录及文件
         */
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            FileWriter writer=null;
            try {
                String info = rt_text.getText().toString();
                writer = new FileWriter(file2);
                writer.write(info);
                // 清空
                writer.flush();
                Toast.makeText(this, "已写入", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if (writer!=null){
                    try {
                        // 关闭
                        writer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public void write_byte2() {
        String stateString = Environment.getExternalStorageState();
        if (stateString.equals(Environment.MEDIA_MOUNTED)) {
            String infoString = rt_text.getText().toString();
            RandomAccessFile ref=null;
            try {
                // rw表示该文件可以被读和写
               ref = new RandomAccessFile(file2, "rw");
                // 将游标移至文本框信息的最后
                ref.seek(file2.length());
                // 写入数据
                ref.write(infoString.getBytes());
                Toast.makeText(this, "已写入", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if (ref != null) {
                    try {
                        // 关闭
                        ref.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    // 字节读写入SD卡
    public void write_byte() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            String info = rt_text.getText().toString();
            FileOutputStream fos=null;
            // 可以理解为打开通向这个路径的通道
            try {
                fos = new FileOutputStream(file2);
                fos.write(info.getBytes());
                Toast.makeText(this, "已写入", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if (fos != null) {
                    try {
                        // 关闭
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    // 字符流读取SD卡文件
    public void read_char() {
        StringBuilder builder = new StringBuilder();
        String line = null;
        FileInputStream fis=null;
        BufferedReader reader=null;
        try {
            fis = new FileInputStream(file2);
            reader = new BufferedReader(new InputStreamReader(
                    fis));
            while ((line=reader.readLine())!=null) {
                builder.append(line);
            }
            reader.close();
            fis.close();
            tv_text.setText(builder.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fis != null) {
                try {
                    // 关闭
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    // 关闭
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 字节流读取SD卡文件
    public void read_byte() {
        byte[] bty = new byte[1024];
        // StringBuilder
        // StringBuffer
        // String
        StringBuilder builder = new StringBuilder();
        // 打开了通向text.txt文件通道
        FileInputStream fis=null;
        try {
            fis = new FileInputStream(file2);
            int read_int = -1;
            while ((read_int = fis.read(bty)) != -1) {
                String str = new String(bty, 0, read_int);
                // 每一次取出来的数据进行拼接
                builder.append(str);
            }
            tv_text.setText(builder.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fis != null) {
                try {
                    // 关闭
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}

end,还不会的同学赶快敲起来哦

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

有头发的猿

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

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

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

打赏作者

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

抵扣说明:

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

余额充值