Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

swift文件相关的操作 #168

Open
platojobs opened this issue Apr 11, 2022 · 0 comments
Open

swift文件相关的操作 #168

platojobs opened this issue Apr 11, 2022 · 0 comments
Labels
MobileDevelopment iOS、安卓、Flutter、go

Comments

@platojobs
Copy link
Owner

platojobs commented Apr 11, 2022

1. 路径


let path1 = "/Users/pj/Downloads/1.html"
let path2 = "/Users/pj/Documents/GitHub/"

let u1 = URL(string: path1)
do {
    // 写入
    let url1 = try FileManager.default.url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: u1, create: true) // 保证原子性安全保存
    print(url1)

    // 读取
    let s1 = try String(contentsOfFile: path1, encoding: .utf8)
    print(s1)

} catch {}

// 检查路径是否可用
let u2 = URL(fileURLWithPath:path2)
do {
    let values = try u2.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])
    if let capacity = values.volumeAvailableCapacityForImportantUsage {
        print("可用: \(capacity)")
    } else {
        print("不可用")
    }
} catch {
    print("错误: \(error.localizedDescription)")
}

2. 遍历路径下所有目录

// 遍历路径下所有目录
let u3 = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
let fm = FileManager.default
fm.enumerator(atPath: u3.path)?.forEach({ path in
    guard let path = path as? String else {
        return
    }
    let url = URL(fileURLWithPath: path, relativeTo: u3)
    print(url.lastPathComponent)
})

3. FileWrapper 的使用

// FileWrapper 的使用
// 创建文件
let f1 = FileWrapper(regularFileWithContents: Data("# 第 n 个文件\n ## 标题".utf8))
f1.fileAttributes[FileAttributeKey.creationDate.rawValue] = Date()
f1.fileAttributes[FileAttributeKey.modificationDate.rawValue] = Date()
// 创建文件夹
let folder1 = FileWrapper(directoryWithFileWrappers: [
    "file1.md": f1
])
folder1.fileAttributes[FileAttributeKey.creationDate.rawValue] = Date()
folder1.fileAttributes[FileAttributeKey.modificationDate.rawValue] = Date()

do {
    try folder1.write(
        to: URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appendingPathComponent("NewFolder"),
        options: .atomic,
        originalContentsURL: nil
    )
} catch {}
print(FileManager.default.currentDirectoryPath)
@platojobs platojobs changed the title 🐶 168 Jul 22, 2022
@platojobs platojobs changed the title 168 swift文件相关的操作 Jul 10, 2024
@platojobs platojobs added the MobileDevelopment iOS、安卓、Flutter、go label Jul 10, 2024
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
MobileDevelopment iOS、安卓、Flutter、go
Projects
None yet
Development

No branches or pull requests

1 participant