Android复习之旅--文件存储

版权声明:本文为博主原创文章,转载需注明出处,谢谢。 https://blog.csdn.net/fengrixin/article/details/52974031

内部存储

内部存储是指将应用程序中的数据以文件方式存储到设备的内部存储空间中(该文件位于 data/data// 目录下)。

一般情况下应用保存在内存下的数据其他应用是访问不了的,当您希望确保用户或其他应用均无法访问您的文件时,内部存储是最佳选择。用户卸载该应用的同时存储在内存中的数据会一并删除。

getFilesDir() :返回该应用的内部目录(data/data//)

在应用目录里新建文件

File file = new File(getFileDir(), filename);

应用中一般会把一些数据存入缓存中,可以减少访问服务器的次数,节省用户的流量

getCacheDir():返回该应用缓存文件的目录(data/data//cache/)

File file = File.createTempFile(fileName, null, context.getCacheDir());

写数据

FileOutputStream openFileOutput(String name, int mode);

/**写文本信息到手机内存中
 * @param filename : 文件名
 * @param body : 文件的内容
 * @throws Exception
 */
public void writePhone(String file, String body) throws Exception {
    FileOutputStream fos = null;
    try {
        fos = context.openFileOutput(file, Context.MODE_PRIVATE);
        fos.write(body.getBytes()); //写文本信息到手机内存中
    } catch (Exception e) {
        if(fos != null){
            fos.close(); //关闭文件输入流
        }
    }
}

其中,mode是读写文件的方式,通常使用的值有2种

  • MODE_PRIVATE:私有模式,只能被当前程序读写
  • MODE_APPEND:追加模式

读数据

FileInputStream openFileInput(String name);

/**从手机内存中读数据
 * @param file : 文件名
 * @return String : 返回读到的文本信息
 */
public String readPhone(String file) throws Exception {
    /**
     * 1、开辟输入流  
     * 2、把读取到的流数据存放到内存流中     
     * 3、返回读取到的信息(String的形式返回)
     */
    FileInputStream fis = context.openFileInput(file);
    //字节数组输出流(内存流)
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];//字节数组,缓存
    int len = -1;
    while((len = fis.read(buffer)) != -1){
        //把读取的内容写入到内存流中
        baos.write(buffer, 0, len);
    }
    baos.close();
    fis.close();
    return baos.toString();
}

外部存储

外部存储是指将文件存储到一些外围设备上,如SDcard或设备内嵌的存储卡等(该文件通常位于mnt/sdcard目录下,由于手机有各种厂商生产,获取SD卡根目录一律采用Environment.getExternalStorageDirectory()这个方法)

由于外围存储设备可能被移除、丢失或者处于其他状态,所以使用外围设备之前要使用Environment.getExternalStorageState()方法来确认是否可用。因为外围存储是全局可读写的,对于无需访问限制以及您希望与其他应用共享或允许用户使用电脑访问的文件,外部存储是最佳位置。

写数据

FileOutputStream 或 FileWriter

/**写文件到sdcard中
 * @param file
 * @param body
 */
public void writeSdcard(String file, String body) throws Exception {
    /**
     * 1、判断sdcard的状态  
     * 2、假如有sdcard,且正常  获取sdcard的根路径,并且通过传过来的文件名进行创建或者打开该文件
     * 3、写数据到输出流   
     * 4、关闭流
     */
    FileOutputStream fos = null;
    try{
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
        //取得sdcard的根路径
        File rootPath = Environment.getExternalStorageDirectory();
        //创建要写入sdcard的文件
        File f = new File(rootPath, file);
        //开辟输出流
        fos = new FileOutputStream(f);
        fos.write(body.getBytes());
    }finally {
        if(fos != null){
            fos.close();
        }else{
            throw new RuntimeException("sdcard状态错误");
        }
    }
}

读数据

FileInputStream 或 FileReader

/**
 * 读取sdcard中的文件
 * @param file
 * @return
 * @throws Exception
 */
public String readSdcard(String file) throws Exception {
    FileInputStream fis = null;
    ByteArrayOutputStream baos = null;
    try{
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            //取得sdcard的根目录
            File rootPath = Environment.getExternalStorageDirectory();
            File f = new File(rootPath.getAbsolutePath()+ "/" + file);
            if(f.exists()){ //判断文件是否存在
                fis = new FileInputStream(f);
                //字节数组输出流(内存流)
                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024]; //字节数组,缓存
                int len = -1;
                while((len = fis.read(buffer)) != -1){
                    //把读取到的内容写入到内存流中
                    baos.write(buffer, 0, len);
                }
            }else{
                return null;
            } 
        }else{
            throw new RuntimeException("sdcard状态错误");
        }
    } finally{
        if(baos != null){
            baos.close();
        }
        if(fis != null){
            fis.close();
        }
    }
    return baos.toString();
}

需要注意的是,读写外部数据时需要设置权限

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

猜你喜欢

转载自blog.csdn.net/fengrixin/article/details/52974031
今日推荐