Android 文件操作方法
时间:2023-06-02 12:51:17
数据存储与访问常用方式:
文件
SharedPreferences(偏好参数设置)
SQLite数据库
内容提供者(Content provider)
网络
Activity(Context)
Context.getCacheDir()方法用于获取/data/data/<package name>/cache目录
Context.getFilesDir()方法用于获取/data/data/<package name>/files目录
Activity(Context)提供了openFileOutput(filename,mode)方法用于把数据输出到文件中;
第一个参数用于指定文件名称,不能包含路径分隔符‘/'
第二个参数为操作模式:
Context.MODE_PRIVATE:私有操作模式创建出来的文件只能被本程序访问,如果文件不存在,会自动创建,另外:写入文件中的内容会覆盖原文件的内容;
Context.MODE_APPEND:模式会检查文件是否存在,如果存在则会追加内容,否则创建新文件;
Context.MODE_READABLE:表示当前文件可以被其它应用读取;
Context.MODE_WRITEABLE:表示当前文件可以被其它应用写入;
如果希望文件被其它应用读和写:传入(Context.MODE_READABLE+Context.MODE_WRITEABLE)
FileOutputStream outStream = context.openFileOutput(filename,Context.MODE_PRIVATE);
//param 文件名称,操作方式
android有一套自己的安全模型,当应用程序(.apk)在安装时系统会分配给一个userid,当该应用去访问其它资源如文件的时候,会进行 userid的匹配,默认情况下任何应用创建的文件,sharedpreferences,数据库都是私有的(创建的文件保存在/data/data /<package name>/files目录下),只有指定操作模式为外部可读或写才可以被其它程序访问;
读取文件:
<1>
FileInputStream inStream = context.openFileInput(filename);
Log.i(TAG,inStream....)
<2>
path="/data/data/<package name>/files/hello.txt";
File file = new File(path);
FileInputStream inStream = new FileInputStream(file);
Log.i(TAG,inStream....)
ctrl + shift + x/y 大小写
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android实现简易秒表功能
![](https://img.aspxhome.com/file/2023/6/95986_0s.jpg)
MyBatis-Plus中最简单的查询操作教程(Lambda)
![](https://img.aspxhome.com/file/2023/7/73097_0s.png)
Android实现ImageView图片缩放和拖动
![](https://img.aspxhome.com/file/2023/3/138483_0s.jpg)
java实现滑动验证解锁
![](https://img.aspxhome.com/file/2023/4/74894_0s.jpg)
C#实现图片上传与浏览切换的方法
java中String字符串删除空格的七种方式
![](https://img.aspxhome.com/file/2023/1/63311_0s.jpg)
Android RecyclerView加载不同布局简单实现
![](https://img.aspxhome.com/file/2023/9/139219_0s.gif)
Android中使用Spinner实现下拉列表功能
![](https://img.aspxhome.com/file/2023/8/139128_0s.gif)
Java线程中断interrupt的常用方法
webuploader 实现图片批量上传功能附实例代码
![](https://img.aspxhome.com/file/2023/8/67148_0s.png)
执行java请求时导致在脚本执行结束时JVM无法退出
轻松实现功能强大的Android刮奖效果控件(ScratchView)
![](https://img.aspxhome.com/file/2023/3/122053_0s.gif)
Android 管理Activity中的fragments
![](https://img.aspxhome.com/file/2023/7/137197_0s.png)
spring boot使用logback实现多环境日志配置详解
![](https://img.aspxhome.com/file/2023/3/99853_0s.png)
Android自定义控件实现UC浏览器语音搜索效果
![](https://img.aspxhome.com/file/2023/6/117146_0s.jpg)
Java服务器主机信息监控工具类的示例代码
![](https://img.aspxhome.com/file/2023/0/57730_0s.png)
spring boot加载第三方jar包的配置文件的方法
java读取excel文件的两种方法
![](https://img.aspxhome.com/file/2023/4/87364_0s.png)
Android Room数据库多表查询的使用实例
![](https://img.aspxhome.com/file/2023/4/114314_0s.jpg)
Android仿百度福袋红包界面
![](https://img.aspxhome.com/file/2023/2/138232_0s.jpg)