只有记在脑海里的才是自己的,如果还没来得及,请写下来
swift 常用文件操作
2020-11-25 / 2 min read
let path = NSHomeDirectory() + "/Documents/" + name

1:判断文件/文件夹是否存在

var isDirectory: ObjCBool = false       // 是否为文件夹
let fileExists: Bool = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory)
if fileExists {
    // 文件/文件夹存在
    if isDirectory.boolValue {
        // 文件夹
    }else {
        // 文件
    }
}

2:创建文件,创建目录

  1. 创建文件
let path = NSHomeDirectory() + "/Documents/" + name.plist
do {
    try fm.createFile(atPath: path, contents: nil, attributes: nil)
}catch {
    debugPrint("\(error)")
}
  1. 创建目录
let path = NSHomeDirectory() + "/Documents/" + "/name/test"
do {
    fm.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)   // withIntermediateDirectories 表示创建中间目录
}catch {
    debugPrint("\(error)")
}

3:删除文件

do {
    try FileManager.default.removeItem(atPath: path)
}catch {
    debugPrint("\(error)")
}

4:写入数据\读取数据

  1. 写入数据
let da: Data = .....
do {
    try da.write(to: URL.init(fileURLWithPath: filePath), options: Data.WritingOptions.atomicWrite)
}catch {
    debugPrint("\(error)")
}
  1. 读取数据
do {
    let data = try Data.init(contentsOf: URL.init(fileURLWithPath: filePath))
    return data
}catch {
    debugPrint("\(error)")
}