Cangjie 标准库 std.fs 目录操作实战:Directory 类创建、查询与遍历完全指南

原创2026-10-14 13:10:37449 阅读
文章标签:人工智能AI 技能文档开发工具

Cangjie 标准库 std.fs 目录操作实战:Directory 类创建、查询与遍历完全指南

导读

Directory 是 Cangjie 标准库 std.fs(文件系统)包中对应文件系统目录的核心类,它提供了目录的创建(含递归创建)、临时目录创建、空目录判断、子项目列表读取与目录遍历等能力,是日常文件系统编程中高频使用的基础工具类。本文将围绕 Directory 类全部 5 组静态成员函数展开,结合 std.fs 包内的路径(Path)、文件元数据(FileInfo)与异常体系,给出可直接复制运行的 Cangjie 代码示例,帮助你快速掌握目录操作的正确姿势与边界行为。

本文内容以 Directory_class.md 为骨架,并融合了 fs 包 API 详解、目录操作示例 与 Path 示例 等仓库文档,所有代码均可对照仓库中的对应文档进一步阅读。

一、Directory 类概览:能力定位与设计要点

1.1 类的声明与定位

在 Cangjie 标准库 std.fs 中,Directory 被定义为无状态的工具类,全部能力以静态成员函数形式对外提供:

public class Directory {}

从 fs 包整体架构看,Directory 与 File、HardLink、SymbolicLink 共同构成了"文件与目录实体"这一能力分组,具体划分见 fs_package_readme.json 与 readme.md。它的职责非常聚焦:

  • 创建目录(含递归逐级创建);
  • 创建临时目录;
  • 判断目录是否为空;
  • 读取目录下的子项目(子文件/子目录)列表;
  • 非递归遍历目录子项目并执行回调。

至于目录的移动、复制、删除、重命名等操作,则不在 Directory 类内部,而是由 std.fs 包级函数 copy、rename、remove、removeIfExists 提供(详见 fs_package_funcs.md),阅读时可配套理解。

1.2 Path / String 双重载设计

Directory 的每一组静态函数都提供 Path 与 String 两种重载,例如:

名称 原型(Path 版) 原型(String 版)
create (path: Path, recursive!: Bool = false): Unit (path: String, recursive!: Bool = false): Unit
createTemp (directoryPath: Path): Path (directoryPath: String): Path
isEmpty (path: Path): Bool (path: String): Bool
readFrom (path: Path): Array<FileInfo> (path: String): Array<FileInfo>
walk (path: Path, f: (FileInfo)->Bool): Unit (path: String, f: (FileInfo)->Bool): Unit

两种重载行为完全一致,选择哪种取决于调用方手头的数据类型。注意命名参数 recursive! 与 to! 等使用了 Cangjie 的命名参数语法(以 ! 结尾表示命名参数),调用时需写 Directory.create(path, recursive: true)。

1.3 非法路径的统一定义

在使用目录相关 API 之前,必须先明确 std.fs 对非法路径的统一约定(fs_package_classes.md):

  • 路径中包含非法字符,例如空格、制表符、换行符等;
  • 路径中包含不合法的字符,例如特殊字符、控制字符等;
  • 路径中包含不存在的目录或文件;
  • 路径中包含无法访问的目录或文件,例如权限不足或被锁定等。

此外,Path 结构体文档 明确指出:路径的字符串最大支持 4096 个字节(包括结束符 \0)。输入路径时应避免非法字符,确保路径合法性,以便正确访问目标目录。

二、创建目录:Directory.create

2.1 函数签名与参数语义

public static func create(path: Path, recursive!: Bool = false): Unit
public static func create(path: String, recursive!: Bool = false): Unit

参数说明:

参数 类型 说明
path Path / String 待创建的目录路径
recursive! Bool 是否递归创建,true 表示递归创建,false 表示不递归,默认值为 false

recursive! 为 true 时,函数会逐级创建路径中所有不存在的中间目录。例如 Directory.create(Path("./a/b/c"), recursive: true) 会依次创建 a、a/b、a/b/c。

2.2 异常行为

  • FSException:目录已存在时抛出异常;非递归创建时中间目录不存在也会抛出异常;
  • IllegalArgumentException:目录为空、目录为当前目录(如 .)、目录为根目录(如 /)或目录中存在空字符时抛出异常。

因此,非递归创建目录要求其父目录必须已经存在;而重复创建同一目录会直接抛异常——在实际代码中常与 exists 函数配合判断后再创建。

2.3 实战示例

import std.fs.*

main() {
    let dirPath: Path = Path("./testDir")
    // 目录已存在时先递归删除,避免 create 抛异常
    if (exists(dirPath)) {
        remove(dirPath, recursive: true)
    }
    // 非递归创建
    Directory.create(dirPath)
    // 递归创建多级目录
    Directory.create(Path("./testDir/a/b/c"), recursive: true)
    return 0
}

仓库中 directory_samples.md 给出了经过验证的完整示例:先通过 exists 判断并用 remove(testDirPath, recursive: true) 清理旧目录,再调用 Directory.create(subDirPath, recursive: true) 递归创建 ./testDir/subDir,随后用 exists(subDirPath) 校验创建结果。

三、创建临时目录:Directory.createTemp

3.1 函数签名与返回值

public static func createTemp(directoryPath: Path): Path
public static func createTemp(directoryPath: String): Path
  • 功能:在指定目录下创建临时目录;
  • 返回值:Path,即新建临时目录对应的路径;
  • 参数 directoryPath 必须指向一个已存在的目录。

3.2 异常行为

3.3 典型用途

createTemp 常用于需要"在运行期间安全地暂存中间产物、且结束后整体清理"的场景。与 File.createTemp 创建的临时文件(文件名形如 tmpFileXXXXXX,见 fs_package_classes.md)不同,Directory.createTemp 创建的是目录,返回的 Path 可以直接用于 join 拼接子路径:

import std.fs.*

main() {
    let testDirPath: Path = Path("./testDir")
    if (!exists(testDirPath)) {
        Directory.create(testDirPath)
    }
    // 在 ./testDir 下创建临时目录
    let tempDirPath: Path = Directory.createTemp(testDirPath)
    if (exists(tempDirPath)) {
        println("The temporary directory is created successfully in directory './testDir'.")
    }
    // 在临时目录内继续创建子目录/文件
    let subPath: Path = tempDirPath.join("subDir_new")
    Directory.create(subPath)
    return 0
}

四、判断目录是否为空:Directory.isEmpty

4.1 函数签名与返回值语义

public static func isEmpty(path: Path): Bool
public static func isEmpty(path: String): Bool
  • 功能:判断指定目录是否为空;
  • 返回值:Bool,true 表示目录为空,false 表示不为空。

4.2 异常行为

  • FSException:指定路径不存在、指定路径不是目录,或判断过程中底层调用的系统接口发生错误,均抛出异常;
  • IllegalArgumentException:指定路径为空或包含空字符时抛出异常。

4.3 使用注意

由于 isEmpty 对"路径不存在"也会抛异常,调用前建议先用 exists 确认目标存在,或用 try/catch 捕获 FSException。典型应用场景:删除目录前的安全检查、判断空目录以决定是否复用等。

五、读取目录子项目列表:Directory.readFrom

5.1 函数签名与返回值

public static func readFrom(path: Path): Array<FileInfo>
public static func readFrom(path: String): Array<FileInfo>
  • 功能:获取指定目录下的直接子项目(子文件与子目录)列表;
  • 返回值:Array<FileInfo>,数组元素为 FileInfo 结构体实例;
  • 排序语义:子项目在数组中的顺序取决于文件在系统中的排序(即系统底层目录读取顺序),并非按名称字典序的保证。

5.2 异常行为

  • FSException:路径不存在、路径不是目录或获取目录成员信息失败时抛出异常;
  • IllegalArgumentException:路径为空或包含空字符时抛出异常。

5.3 结合 FileInfo 读取子项目属性

readFrom 返回的每个 FileInfo 都对应一个子文件或子目录,可结合 FileInfo 结构体 的能力继续深入查询:

FileInfo 属性/方法 含义
name 文件名或目录名(等价于 this.path.fileName)
path 当前文件/目录的 Path
size 文件大小(目录时表示该目录内所有文件占用磁盘空间的大小)
isDirectory() / isRegular() 判断是目录还是普通文件
isHidden() / isReadOnly() / isSymbolicLink() 隐藏、只读、软链接判断
creationTime / lastModificationTime / lastAccessTime 创建/修改/访问时间
canRead() / canWrite() / canExecute() 权限判断
parentDirectory 父级目录元数据(Option<FileInfo>)

一个典型的列目录程序:

import std.fs.*

main() {
    let dirPath: Path = Path("./testDir")
    if (!exists(dirPath)) {
        Directory.create(dirPath)
    }
    // 读取目录下所有子项目
    let items: Array<FileInfo> = Directory.readFrom(dirPath)
    for (info in items) {
        let typeStr: String = if (info.isDirectory()) { "DIR " } else { "FILE" }
        println("${typeStr} ${info.name}  size=${info.size}")
    }
    return 0
}

注意 FileInfo 底层实现 没有缓存文件属性,每次通过其 API 获取的都是现场读取的最新属性。若两次获取之间文件实体被其他进程修改或替换,后一次获取的可能不是期望的属性;对有特殊一致性要求的场景,可通过设置文件权限或对关键操作加锁来保证。

六、非递归遍历目录:Directory.walk

6.1 函数签名与回调语义

public static func walk(path: Path, f: (FileInfo)->Bool): Unit
public static func walk(path: String, f: (FileInfo)->Bool): Unit

参数:

参数 类型 说明
path Path / String 待遍历的目录路径
f (FileInfo) -> Bool 对每一个子项目执行的回调函数,入参为子项目对应的 FileInfo 元信息,返回值表示是否继续遍历

walk 的退出条件为:遍历结束 或 回调函数 f 返回 false。遍历顺序同样取决于文件在系统中的排序。

需要特别强调的是:walk 是非递归遍历,即只遍历 path 目录下的直接子项目,不会深入子目录。若需要递归遍历整棵目录树,需在回调中对 isDirectory() 为 true 的子项目自行递归调用 walk。

6.2 异常行为

  • FSException:路径不存在、路径不是目录或获取目录成员信息失败时抛出异常;
  • IllegalArgumentException:路径为空或包含空字符时抛出异常。

6.3 实战示例:提前终止遍历

回调返回 false 即可提前终止,适合"找到目标就停止"的场景:

import std.fs.*

main() {
    let dirPath: Path = Path("./testDir")
    if (!exists(dirPath)) {
        Directory.create(dirPath, recursive: true)
    }
    var found: Bool = false
    // 遍历目录,找到第一个目录类型的子项目后终止
    Directory.walk(dirPath) { info =>
        println("visit: ${info.name}")
        if (info.isDirectory()) {
            found = true
            return false   // 返回 false 提前终止遍历
        }
        return true        // 返回 true 继续遍历
    }
    if (found) {
        println("found a subdirectory.")
    }
    return 0
}

6.4 与 readFrom 的取舍

  • 需要完整拿到所有子项目做后续处理(排序、过滤、批量操作)时,用 readFrom 返回 Array<FileInfo> 更顺手;
  • 需要逐个处理且可能提前终止(如搜索、统计、命中即停)时,用 walk 配合回调更省内存、更灵活。

七、综合实战:目录创建—写入—遍历—清理完整流程

下面把 Directory 的 5 组方法与 std.fs 包级函数(exists、remove、rename、copy、canonicalize)以及 File 类、Path 结构体 组合成一个完整的、可直接运行的目录管理示例(综合自 directory_samples.md 与 path_samples.md 的思路):

import std.fs.*

main() {
    let testDirPath: Path = Path("./testDir")
    let subDirPath: Path = Path("./testDir/subDir")
    // 清理历史残留,避免 create 重复创建抛异常
    if (exists(testDirPath)) {
        remove(testDirPath, recursive: true)
    }

    // 1) 递归创建目录 ./testDir/subDir
    Directory.create(subDirPath, recursive: true)
    if (exists(subDirPath)) {
        println("The directory './testDir/subDir' is successfully created recursively.")
    }

    // 2) 在 ./testDir 下创建临时目录
    let tempDirPath: Path = Directory.createTemp(testDirPath)
    if (exists(tempDirPath)) {
        println("The temporary directory is created successfully in './testDir'.")
    }

    // 3) 移动并重命名目录
    let newSubDirPath: Path = tempDirPath.join("subDir_new")
    rename(subDirPath, to: newSubDirPath)
    if (exists(newSubDirPath) && !exists(subDirPath)) {
        println("'subDir' is moved to temporary directory and renamed 'subDir_new'.")
    }

    // 4) 拷贝目录并重命名
    copy(newSubDirPath, to: subDirPath, overwrite: false)
    if (exists(subDirPath) && exists(newSubDirPath)) {
        println("'subDir_new' is copied to './testDir' and renamed 'subDir'.")
    }

    // 5) 读取与遍历
    let items: Array<FileInfo> = Directory.readFrom(testDirPath)
    println("readFrom size: ${items.size}, isEmpty: ${Directory.isEmpty(testDirPath)}")
    Directory.walk(testDirPath) { info =>
        println("walk visit: ${info.name}")
        return true
    }

    // 6) 规范化路径
    let abs: Path = canonicalize(testDirPath)
    println("canonicalize: ${abs}")

    // 7) 清理
    remove(testDirPath, recursive: true)
    return 0
}

上述流程覆盖了:递归创建 → 临时目录 → 移动重命名 → 拷贝 → 读取/遍历/空判断 → 路径规范化 → 递归删除。运行结果可参考 directory_samples.md 中给出的英文输出样例。

八、配套理解:fs 包协同 API 与异常体系

8.1 与 Directory 高频协同的包级函数

函数 原型 说明
exists (Path): Bool 判断目标地址是否存在(调用目录类 API 前的标准前置检查)
remove (Path, recursive!: Bool = false): Unit 删除文件或目录,目录可递归删除
removeIfExists (Path, recursive!: Bool = false): Bool 存在则删除并返回 true
rename (sourcePath, to!, overwrite!: Bool = false): Unit 重命名/移动文件或目录
copy (sourcePath, to!, overwrite!: Bool = false): Unit 复制文件或目录
canonicalize (Path): Path 获取绝对路径形式的规范化路径

值得注意的细节(fs_package_funcs.md):

  • rename 的 overwrite: true 会删除目标位置的原有文件或目录;若目标为目录会递归删除其中所有内容,需谨慎使用;
  • copy 在 overwrite: true 时要求源与目标的类型一致(目录对目录、常规文件对常规文件、符号链接对符号链接),否则抛 FSException;
  • remove 删除非空目录时若未指定 recursive: true 会失败抛异常。

8.2 异常体系

目录操作涉及两类异常(详见 fs_package_exceptions.md 与 core 包异常):

  • FSException:文件系统异常类,继承自 IOException(位于 io 包),提供无参 init() 与带消息 init(message: String) 两种构造方式,覆盖"目录已存在""路径不存在""底层系统调用失败"等场景;
  • IllegalArgumentException:参数非法异常,覆盖"路径为空""包含空字符""目录为当前目录/根目录"等场景。

8.3 平台支持

根据 fs_package_overview.md,std.fs 包目前支持 Linux、macOS、Windows 和 HarmonyOS 平台。路径分隔符等平台差异(如 Windows 为 \,其余平台为 /)由 Path 结构体 的静态常量 Separator、ListSeparator 统一抽象,跨平台代码建议优先使用 Path.join 拼接路径而非手写分隔符。

九、Directory 类 API 速查表

静态函数 原型 关键行为
create (path: Path/String, recursive!: Bool = false): Unit 创建目录;recursive: true 时逐级创建缺失的中间目录;目录已存在抛 FSException
createTemp (directoryPath: Path/String): Path 在指定目录下创建临时目录并返回其 Path
isEmpty (path: Path/String): Bool 判断目录是否为空;路径不存在或不是目录抛 FSException
readFrom (path: Path/String): Array<FileInfo> 返回直接子项目列表,顺序取决于系统排序
walk (path: Path/String, f: (FileInfo)->Bool): Unit 非递归遍历直接子项目;回调返回 false 提前终止

参考文档索引

登录后查看全文
DocAgent