如何使用NSFileManager来操作文件系统

发布时间:2024-06-03 12:16:06 作者:小樊
来源:亿速云 阅读:90

NSFileManager是iOS和macOS中用于管理文件系统的类,可以用来创建、复制、移动、删除文件和目录,以及获取文件和目录的属性等操作。下面是一些常见的NSFileManager使用方法:

  1. 创建文件夹:
let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
let folderURL = documentsURL.appendingPathComponent("FolderName")

do {
    try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true, attributes: nil)
} catch {
    print("Error creating folder: \(error)")
}
  1. 复制文件:
let sourceURL = URL(fileURLWithPath: "path/to/source/file")
let destinationURL = URL(fileURLWithPath: "path/to/destination/file")

do {
    try fileManager.copyItem(at: sourceURL, to: destinationURL)
} catch {
    print("Error copying file: \(error)")
}
  1. 移动文件:
let sourceURL = URL(fileURLWithPath: "path/to/source/file")
let destinationURL = URL(fileURLWithPath: "path/to/destination/file")

do {
    try fileManager.moveItem(at: sourceURL, to: destinationURL)
} catch {
    print("Error moving file: \(error)")
}
  1. 删除文件或文件夹:
let fileURL = URL(fileURLWithPath: "path/to/file")

do {
    try fileManager.removeItem(at: fileURL)
} catch {
    print("Error deleting file: \(error)")
}
  1. 获取文件或文件夹属性:
let fileURL = URL(fileURLWithPath: "path/to/file")

do {
    let attributes = try fileManager.attributesOfItem(atPath: fileURL.path)
    print(attributes)
} catch {
    print("Error getting file attributes: \(error)")
}

这些是一些基本的NSFileManager的用法,根据实际需求可以进一步扩展和应用。

推荐阅读:
  1. Foundation中如何利用NSExpression进行数学运算
  2. Foundation中NSLinguisticTagger如何用于文本分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

foundation

上一篇:解释Foundation中的Key-Value Coding

下一篇:NSUserDefaults的使用场景有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》