分享

关于android里的文件创建及读写问题

 JUST SO LAZY 2013-01-22

关于android里的文件创建及读写问题

(2012-11-21 15:00:53)

一 在SD卡创建并读写文件

   SD卡正常加载后,通过Eclipse的DDMS的File explorer可以看到 mnt/sdcard的权限属性为d---rwxr-x,很奇怪的属性,sdcard的owner是system用户,但system用户对sdcard没有读写可执行权限,所以如果需要对sdcard操作,就不能是system用户。

   读写SD卡需要在app的manifest中添加

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />申请权限

   然后在java文件里

   File newxmlfile = new File(Environment.getExternalStorageDirectory(),"aaa.xml");

       try{
         if(!newxmlfile.exists())
                newxmlfile.createNewFile();
        }catch(IOException e){
            Log.e("IOException", "exception in createNewFile() method");
            return;
        }
        //we have to bind the new file with a FileOutputStream
        FileOutputStream fileos = null;       
        try{
            fileos = new FileOutputStream(newxmlfile);
           }catch(FileNotFoundException e){
            Log.e("FileNotFoundException", "can't create FileOutputStream");
            return;
        }

  上面是创建并写文件,如果是读就用FileInputStream

二 在data目录创建并读写文件

   android的应用如果想在data目录下创建文件,只能用android提供的方法

   FileOutputStream fileos = null;       
        try{
         fileos=context.openFileOutput("aaa.xml",Context.MODE_WORLD_READABLE);
        }catch(FileNotFoundException e){
            Log.e("FileNotFoundException", "can't create FileOutputStream");
            return;
        }

    其中context是该android应用的ApplicationContext,上面这种方法会查看/data/data/mypackage /files目录下是否有aaa.xml文件,如果没有,则会自动创建(files目录也是自动创建 的),Context.MODE_WORLD_READABLE是参数,代表aaa.xml可以被其他应用读。共有四种参数,这里不做介绍了。

    如果app想在data的其他目录下创建文件,是不会成功的。比如在/data根目录下创建文件,会抛出异常,但可以读/data目录下的文件,也可以对/data下文件修改。

   如果想读文件,有两种方法

   方法一(android提供的方法)

   FileInputStream fis= null;       
        try{
         fis=context.openFileInput("aaa.xml");
        }catch(FileNotFoundException e){
            Log.e("FileNotFoundException", "Couldn't find or open policy file");
            return;
        }

  这种方法读的是/data/data/mypackage/files目录下的aaa.xml

方法二(普通方法)

   File policyFile = new File("/data/aaa.xml");
        FileInputStream fis=null;
        try {
            fis = new FileInputStream(policyFile);
        } catch (FileNotFoundException e) {
            Log.w(TAG, "Couldn't find or open policy file " + policyFile);
            return null;
          

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多