Android入门之文件系统操作(二)文件操作相关指令

时间:2023-03-09 16:39:55
Android入门之文件系统操作(二)文件操作相关指令

(一)获取总根

  1. File[] fileList=File.listRoots();
  2. //返回fileList.length为1
  3. //fileList.getAbsolutePath()为"/"
  4. //这就是系统的总根

(二)打开总根目录

  1. File file=new File("/");
  2. File[] fileList=file.listFiles();
  3. //获取的目录中除了"/sdcard"和"/system"还有"/data"、"/cache"、"/dev"等
  4. //Android的根目录并不像Symbian系统那样分为C盘、D盘、E盘等
  5. //Android是基于Linux的,只有目录,无所谓盘符

(三)获取系统存储根目录

  1. File file=Environment.getRootDirectory();//File file=new File("/system");
  2. File[] fileList=file.listFiles();
  3. //这里说的系统仅仅指"/system"
  4. //不包括外部存储的手机存储的范围远远大于所谓的系统存储

(四)获取SD卡存储根目录

  1. File file=Environment.getExternalStorageDirectory();//File file=new File("/sdcard");
  2. File[] fileList=file.listFiles();
  3. //要获取SD卡首先要确认SD卡是否装载
  4. boolean is=Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
  5. //如果true,则已装载
  6. //如果false,则未装载

(五)获取data根目录

  1. File file=Environment.getDataDirectory();//File file=new File("/data");
  2. File[] fileList=file.listFiles();
  3. //由于data文件夹是android里一个非常重要的文件夹,所以一般权限是无法获取到文件的,即fileList.length返回为0

(六)获取私有文件路径

  1. Context context=this;//首先,在Activity里获取context
  2. File file=context.getFilesDir();
  3. String path=file.getAbsolutePath();
  4. //此处返回的路劲为/data/data/包/files,其中的包就是我们建立的主Activity所在的包
  5. //我们可以看到这个路径也是在data文件夹下
  6. //程序本身是可以对自己的私有文件进行操作
  7. //程序中很多私有的数据会写入到私有文件路径下,这也是android为什么对data数据做保护的原因之一

(七)获取文件(夹)绝对路径、相对路劲、文件(夹)名、父目录

  1. File file=……
  2. String relativePath=file.getPath();//相对路径
  3. String absolutePath=file.getAbsolutePath();//绝对路径
  4. String fileName=file.getName();//文件(夹)名
  5. String parentPath=file.getParent();//父目录

(八)列出文件夹下的所有文件和文件夹

  1. File file=……
  2. File[] fileList=file.listFiles();

(九)判断是文件还是文件夹

  1. File file=……
  2. boolean is=file.isDirectory();//true-是,false-否

(十)判断文件(夹)是否存在

  1. File file=……
  2. boolean is=file.exists();//true-是,false-否

(十一)新建文件(夹)

  1. File file=……
  2. oolean is=file.isDirectory();//判断是否为文件夹
  3. /*方法1*/
  4. if(is){
  5. String path=file.getAbsolutePath();
  6. String name="ABC";//你要新建的文件夹名或者文件名
  7. String pathx=path+name;
  8. File filex=new File(pathx);
  9. boolean is=filex.exists();//判断文件(夹)是否存在
  10. if(!is){
  11. filex.mkdir();//创建文件夹
  12. //filex.createNewFile();//创建文件
  13. }
  14. /*方法2*/
  15. if(is){
  16. String path=file.getAbsolutePath();
  17. String name="test.txt";//你要新建的文件夹名或者文件名
  18. File filex=new File(path,name);//方法1和方法2的区别在于此
  19. boolean is=filex.exists();//判断文件(夹)是否存在
  20. if(!is){
  21. filex.mkdir();//创建文件夹
  22. //filex.createNewFile();//创建文件
  23. }

(十二)重命名文件(夹)

  1. File file=……
  2. String parentPath=file.getParent();
  3. String newName="name";//重命名后的文件或者文件夹名
  4. File filex=new File(parentPath,newName);//File filex=new File(parentPaht+newName)
  5. file.renameTo(filex);

(十三)删除文件(夹)

    1. File file=……
    2. file.delete();//立即删除
    3. //file.deleteOnExit();//程序退出后删除,只有正常退出才会删除