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

一 在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 = newFile(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(FileNotFoundExceptione){
           Log.e("FileNotFoundException", "can't createFileOutputStream");
           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 createFileOutputStream");
           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 policyfile");
           return;
       }

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

方法二(普通方法)

   FilepolicyFile = 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值