Anfroid文件保存,加载
来源:互联网 发布:网络拾贝 编辑:程序博客网 时间:2024/05/22 04:23
安卓存取文件方法与java很像,可以直接使用java中的文件流,而需要注意的是:我们写的android程序,是要将文件保存在手机的sd卡中,所以文件的存取路径是android存取文件的重点。
那么在android中该将文件存在哪呢?通过ADT的ddms可以看到android的文件系统结构,如图1,如果在写程序的时候,不写文件路径,如下:
File file = new File("info.dat");则info.dat将存放在 “data/app/” 路径下。
但是如果这样写,程序会抛出异常。这是因为这个路径是只读的。所以这个路径并不是应用程序保存文件正确的路径。
通过观察ddms里的文件浏览器,我们可以发现一个特点,就是在"/data/data"路径下,对于每个应用程序都存在一个与应用程序关联的文件夹,那么每个文件夹的名称就是应用程序默认包的包名。
那么这些文件夹就是我们要找的正确的文件存储位置。
File file = new File("data/data/com.study.login/info.dat");
但是,我们通常不会以这种硬代码的方式书写程序,那么如何能获取应用程序的所在文件夹路径呢。我们可以借助上下文类Context。(“上下文”是一个类, 类中提供了一些方便的api,可以得到应用程序的环境。环境是指 包名 安装路径 资源路径 资产路径等)。获取方法如下:
File file = new File(context.getFilesDir(),"info.dat");
至此,我们就获得了正确的文件路径。
方法完整代码如下:
//写文件
public class LoginService {public static boolean saveUserInfo(Context context,String username,String password){//文件应该保存在手机中 /data/data/包名/ 目录下try {//硬代码//File file = new File("data/data/com.study.login/info.dat");//context.getFilesDir() 帮助返回一个目录/data/data/包名/files/ //context.getCacheDir() 帮助返回缓存文件夹,文件不要超过1MB//上下文 是一个类, 类中提供了一些方便的api,可以得到应用程序的环境//环境是指 包名 安装路径 资源路径 资产路径File file = new File(context.getFilesDir(),"info.dat");//File file = new File(context.getCacheDir(),"info.dat"); FileOutputStream fos = new FileOutputStream(file);//另外一种读写文件方法:context.openFileOutput(name, mode)fos.write((username+"###"+password).getBytes()); fos.close(); return true;} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();return false;}}//读文件public static Map<String,String> getSaveUserInfo(Context context){Map<String,String> map = new HashMap<String, String>();File file = new File(context.getFilesDir(),"info.dat");FileInputStream fis;try {fis = new FileInputStream(file);BufferedReader reader = new BufferedReader(new InputStreamReader(fis));String info = reader.readLine();String []str = info.split("###");map.put("username", str[0]);map.put("password", str[1]);return map;} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();return null;} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();return null;}}
0 0
- Anfroid文件保存,加载
- 文件加载和保存
- 文件加载与保存
- 文件加载和保存
- 13.文件加载与保存
- 第十五章文件加载与保存
- Unity 保存和加载XML文件
- IOS学习笔记---文件加载和保存
- OpenGL加载、显示、截图、保存位图文件
- ArcEngine加载和保存3dd文件
- 《黑马程序员》 文件加载与保存
- unity 文件、图片加载与保存
- ios的文件加载和保存
- unity 文件、图片加载与保存
- 保存文件到本地and加载本地文件
- 保存MS浏览器控件加载页面到文件
- Object-c学习笔记十六-----文件加载与保存
- [unity3d]保存文件到本地and加载本地文件
- 输入一个字节内的数(0~255)和移动位数。输出移位结果(要求循环移位)提示:系统自带的移位都是非循环的
- 平面最近点对
- sigaction函数嵌套处理信号简单介绍
- “第09课第2节 u-boot分析之Makefile结构分析”之学习笔记
- HDU - 2089 不要62 (暴力或数位DP)
- Anfroid文件保存,加载
- 463 九九乘法表
- jni ndk hal 是啥关系
- HDU_1256 画8
- ldconfig命令简介
- Java内存分配与管理 1
- HDU 3783 ZOJ
- 477 A+B Problem III
- java+内存分配 2