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