Android数据存储

内部存储

内部存储,就是将文件保存在设备内部存储器中,默认情况下,这些文件是相应程序私有的,对其他程序不透明,对用户也是不透明的,当程序卸载后,这些文件就会被删除。

/*
 *从输入框中获取数据,存入内部存储器中,命名为data。
 */
et = (EditText) findViewById(R.id.et);
存数据:
OutputStream os = openFileOutput("data", Context.MODE_PRIVATE);
            os.write(et.getText().toString().getBytes("utf-8"));
            os.flush();
            os.close();
读数据:
InputStream is = openFileInput("data");
            byte[] bytes = new byte[is.available()];
            is.read(bytes);
            is.close();

            String str = new String(bytes,"utf-8");
            et.setText(str);

外部存储:

所有Android设备都支持可以保存文件的共享外部存储器,这个外部存储器可以是可移动存储器(如SD卡),也可以是内置在设备中的外部存储器(不可移动).

File dir = Environment.getExternalStorageDirectory();//获取外部存储器根路径
File dataFile = new File(dir, "data.txt");//在该路径下创建一个文件

//write
        try {
            if (!dataFile.exists()) {
                dataFile.createNewFile();
            }

            FileOutputStream fos = new FileOutputStream(dataFile);
            fos.write(new String("Hello eoe").getBytes("utf-8"));
            fos.flush();
            fos.close();

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

//read
        try {
            FileInputStream fis = new FileInputStream(dataFile);

            byte[] bytes = new byte[fis.available()];
            fis.read(bytes);
            fis.close();

            String str = new String(bytes,"utf-8");
            System.out.println(str);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值