Android开发 - File类文件操作解析

File 是什么

  • File 类用于处理文件和目录。它允许你创建删除读取写入文件。你可以用它来获取文件路径检查文件是否存在获取文件大小等。例如,File file = new File(context.getFilesDir(), "example.txt"); 可以用来在应用的私有目录中创建一个名为 example.txt 的文件

File 构造方法

  • File(String pathname):用一个路径字符串创建一个 File 对象

    File file = new File("/sdcard/example.txt");
    
    • 参数解析
      • pathname文件或目录的完整路径,比如 /sdcard/example.txt
  • File(String parent, String child):用一个父目录路径和一个文件名创建 File 对象

    File file = new File("/sdcard", "example.txt");
    
    • 参数解析
      • parent:父目录路径,比如 /sdcard
      • child:文件或子目录的名字,比如 example.txt
  • File(File parent, String child):用一个父 File 对象和一个文件名创建 File 对象

    File parentDir = new File("/sdcard");
    File file = new File(parentDir, "example.txt");
    
    • 参数解析

      • parent:表示父目录的 File 对象,比如 new File("/sdcard")

      • child文件名子目录名,比如 example.txt

  • File(URI uri):用一个 URI 对象创建 File 对象

    URI uri = new URI("file:///sdcard/example.txt");
    File file = new File(uri);
    
    • 参数解析
      • uri: 统一资源标识符,描述文件的路径,如 file:///sdcard/example.txt

File 主要方法

  • file.exists():检查文件目录是否存在

    File file = new File("/sdcard/example.txt");
    if (file.exists()) {
        // 文件存在
    }
    
  • file.createNewFile()创建新文件(如果它不存在)

    File file = new File("/sdcard/example.txt");
    if (file.createNewFile()) {
        // 文件创建成功
    }
    
  • file.delete()删除文件或空目录

    File file = new File("/sdcard/example.txt");
    if (file.delete()) {
        // 文件删除成功
    }
    
  • file.length()获取文件的大小(字节数)

    File file = new File("/sdcard/example.txt");
    long size = file.length();
    
  • oldFile.renameTo(File dest)重命名文件或移动到新位置

    File oldFile = new File("/sdcard/oldname.txt");
    File newFile = new File("/sdcard/newname.txt");
    if (oldFile.renameTo(newFile)) {
        // 文件重命名成功
    }
    
    • 参数解析
      • dest新文件或新位置
  • files.listFiles()列出目录中的所有文件和子目录

    File dir = new File("/sdcard/mydir");
    File[] files = dir.listFiles();
    if (files != null) {
        for (File file : files) {
            System.out.println(file.getName());
        }
    }
    

构造方法总结

  • File(String pathname)直接通过路径字符串创建文件对象

  • File(String parent, String child)通过父路径和子路径创建文件对象

  • File(File parent, String child)通过父 File 对象和子路径创建文件对象

  • File(URI uri)通过 URI 创建文件对象,适用于处理网络或资源路径

posted @ 2024-08-13 13:31  阿俊学JAVA  阅读(7)  评论(0编辑  收藏  举报