android中数据的存储方式(Internal Storage)

二、Internal Storage(内部存储)

存储应用私有的数据在设备的内存中,其他应用不能访问,当应用卸载,数据也被移除。

1、向内存中写数据的步骤

1)调用openFileOutput(文件名称,文件的操作模式)方法,返回FileOutputStream.对象。

2)使用write()方法向文件中写数据

3)使用close()方法关闭流

2、通过小例子来理解一下

public void writeDate(View view){
        try {
            //得到FileOutputStream对象
            FileOutputStream out = openFileOutput("hello", Context.MODE_PRIVATE);
            //向文件中写数据
            out.write("你是谁,我不认识呢,干啥呀,母鸡啊,over".getBytes());
            //关闭资源,防止内存泄漏
            out.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

3、文件的操作模式

1)MODE_PRIVATE:私有的模式,如果文件同名,会被覆盖

2)MODE_APPEND:可在文件后追加

3)MODE_WORLD_READABLE:只读的

4)MODE_WORLD_WRITEABLE:可写的

都是Context中的,调用时用Context.MODE…

4、从文件中读数据的步骤

1)调用openFileInput(),并传人文件的名称,得到FileInputStream对象

2)调用read()方法读取数据

3)调用close()关闭资源

5、读内存中数据的小例子

public void readDate(View view){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileInputStream inputStream = null;
        try {
            inputStream = openFileInput("hello");
            byte[] bytes = new byte[1024];
            int len = 0;
            if((len = inputStream.read())!=-1){
                //将数据放到缓存流中,缓存流不用关闭
                baos.write(bytes,0,len);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

---------------------------------------------------

三、External Storage(外部存储)

外部存储最简单的例子就是SD卡,使用该种方式存储的数据可以被其他的应用访问。

1、使用外部存储必须给应用添加相应的读写权限

<manifest ...>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    ...
</manifest>

2、外部存储的使用步骤

1)通过getExternalStorageState() 方法获取SD卡的存在状态

2)调用getExternalStoragePublicDirectory()方法获取存储的公共目录

3)存储想要存的内容

3、上代码喽

public void operateSD(View view){
        String state = Environment.getExternalStorageState();
        if(Environment.DIRECTORY_MOVIES.equals(state)){
            //获取文件存储的公共目录
            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"ws");
            //接下来就是对文件的相关操作喽
            if(file.mkdir()){

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值