文件数据存储

一、内部存储

永远可用,因为不可以拆卸。文件默认情况下只对你的APP可用,是私有的。当用户卸载APP时,系统会自定移除APP在内部存储上的所有文件

    //创建和写入一个内部存储的私有文件
    public void WriteFiles(String string) {
        try {
            //填入文件名和操作模式
            FileOutputStream fos = openFileOutput("a.txt", MODE_PRIVATE);
            //通过write()函数写入数据。
            fos.write(string.getBytes());
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //读取一个内部存储的私有文件
    public String readFiles() {
        String string = null;
        try {
            FileInputStream fis = openFileInput("a.txt");
            StringBuilder sb = new StringBuilder();
            byte[] buffer = new byte[1024];
            int len = 0;
            //读取字节
            while ((len = fis.read(buffer)) != -1) {
                sb.append(new String(buffer, 0, len));
            }
            string = sb.toString();
            fis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return string;
    }

二、外部存储

不一定一直可访问,因为用户可以拆卸外部存储设备。文件是全局可度的,没有访问限制,可以和其他APP共享数据

 

    //创建文件
    sdCardDir = Environment.getExternalStorageDirectory();
    saveFile = new File(sdCardDir, "a.txt");
    //获取sd卡状态
    private void storageCard() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            //可读可写
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            // 可读
        } else {
        }
    }

    //写入数据
    public void writeFiles(String string) {
        try {
            FileOutputStream fos = new FileOutputStream(saveFile);
            fos.write(string.getBytes());
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //读取数据
    private String readFiles() {
        String string = null;
        try {
            FileInputStream fis = new FileInputStream(saveFile);
            int len = 0;
            byte[] buf = new byte[1024];
            StringBuffer sb = new StringBuffer();
            while ((len = fis.read(buf)) != -1) {
                sb.append(new String(buf, 0, len));
            }
            string = sb.toString();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return string;
    }

你可能感兴趣的:(文件数据存储)