内部存储是指将应用程序中的数据以文件方式存储到设备的内部(该文件默认位于data/data/<packagename>/files/目录下,该路径挂载再手机自身储存目录),内部存储方式储存的文件被其所创建的应用程序所私有,如果其他应用程序要操作本应用程序中的文件,需要设置权限。当创建的应用程序被卸载时,其内部存储文件也随之删除。

内部存储路径调用的方法是:(通过context调用)

context().getCacheDir().getAbsolutePath()

获取存储路径的方法的代码:

public static String getFilePath(Context context,String dir){
    String directoryPath = "";

    //判断SD卡是否可用
    if(MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
        direcotryPath = context.getExternalFilesDir(dir).getAbsolutePath();
    }else{
        //没内存卡就存手机机身内存中
        directoryPath = context.getFilesDir() + File.separator + dir;
        //directoryPath = context.getCacheDir() + File.separator + dir;
    }
    
    File file = new File(directory);
    //判断文件目录是否已经存在
    if(!file.exits()){  
        file.mkdirs();
    }
    return directoryPath();
}

内部存储存使用的是Context提供的openFileOutput()方法和openFileInput()方法,通过这两个方法可以分别获取FileOutputStream对象和FileInputStream对象,然后进行读写操作。实例代码如下:

FileOutputStream fos = openFileOutput(String name, int mode);
FileInputStream fis = openFileInput(String name);

name:表示文件名

  mode:表示文件的操作方式,如下:

        》MODE_PRIVATE:该文件只能被当前程序读写

        》MODE_APPEND:该文件的内容可以追加

        》MODE_WORLD_READABLE:该文件的内容可以被其他程序读

        》MODE_WORLD_WEITEABLE:该文件的内容可以被其他程序写

示例:

储文件:

String fileName = "text.txt";
String content = "Hello world!";
FileOutputStream fos;
try{
    fos = openFileOutput(fileName,MODE_PRIVATE);
    fos.write(content.getBytes());
    fos.close();
}catch(Exception e){
    e.printStackTrace();
}

文件:

String content = "";
FileInputStream fis;
try{   
    fis = openFileInput("text.txt");
    //创建缓冲区,并获取文件的长度
    byte[] buffer = new byte[fis.available()];
    //将文件内容读取到buffer缓冲区
    fis.read(buffer);
    //转换成字符串
    content = new String(buffer);
    fis.close();
}catch(Exception e){
    e.printStackTrace():
}

简单粗暴!

感谢ლ(°◕‵ƹ′◕ლ)!!!

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐