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

来源:互联网 发布:excel access sql 编辑:程序博客网 时间:2024/05/31 19:14

一 在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;       }