You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何判断文件类型(区分普通文件与目录)

在Swift中区分文件与目录类型

在macOS和Linux上,你可以通过两种常用方法来准确判断文件类型:

方法一:直接用fileExists(atPath:isDirectory:)

这个方法最简洁,能同时判断文件是否存在,以及是否是目录:

import Foundation

let filePath = "/Users/Sample/test.ext"
var isDirectory: ObjCBool = false

if FileManager.default.fileExists(atPath: filePath, isDirectory: &isDirectory) {
    if isDirectory.boolValue {
        print("这是一个目录")
    } else {
        print("这是一个普通文件")
    }
} else {
    print("文件/目录不存在")
}

方法二:通过attributesOfItem(atPath:)获取文件类型属性

如果需要获取更多文件属性(比如权限、创建时间),可以用这个方法,通过FileAttributeKey.type来获取具体类型:

import Foundation

let filePath = "/Users/Sample/test.ext"

do {
    let attributes = try FileManager.default.attributesOfItem(atPath: filePath)
    guard let fileType = attributes[.type] as? FileType else {
        print("无法识别文件类型")
        return
    }
    
    switch fileType {
    case .typeDirectory:
        print("这是一个目录")
    case .typeRegular:
        print("这是一个普通文件")
    case .typeSymbolicLink:
        print("这是一个符号链接")
    // 还可以根据需要处理其他类型,比如.typeSocket、.typeBlockSpecial等
    default:
        print("这是其他类型的文件")
    }
} catch {
    print("获取文件属性失败:\(error.localizedDescription)")
}

注意:第二种方法需要处理异常,因为如果文件不存在或者没有权限访问,会抛出错误。

内容的提问来源于stack exchange,提问作者Marlene

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 17:19:56