如何将文件存储在使用“documentDirectory”swift创建的文件夹中

z8dt9xmd  于 2023-09-30  发布在  Swift
关注(0)|答案(3)|浏览(71)

我创建新的文件夹使用createDirectory与下面的代码。

*let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    // Get documents folder
    let documentsDirectory: String = paths.first ?? ""
    // Get your folder path
    let dataPath = documentsDirectory + "/MyNewFolder"
    print("Path\(dataPath)")
    if !FileManager.default.fileExists(atPath: dataPath) {
        // Creates that folder if no exists
        try? FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: false, attributes: nil)
    }*

现在我想存储新的文件,如log.text下的“MyNewFolder”。任何人都可以建议我如何保存新文件下“我的新文件夹”文件夹
先谢了。

kpbwa7wx

kpbwa7wx1#

NSSearchPathForDirectoriesInDomains已经过时了。推荐使用FileManager的URL相关接口

let folderName = "MyNewFolder"
let fileManager = FileManager.default
let documentsFolder = try! fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let folderURL = documentsFolder.appendingPathComponent(folderName)
let folderExists = (try? folderURL.checkResourceIsReachable()) ?? false
do {
    if !folderExists {
        try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: false)
    }
    let fileURL = folderURL.appendingPathComponent("log.txt")
    let hello = Data("hello".utf8)
    try hello.write(to: fileURL)
    
} catch { print(error) }

强烈建议不要通过连接字符串来构建路径。

更新:

在iOS 16+,macOS 13+中,Apple移动了API以将标准文件夹的URL导入URLappendingPathComponent也已更改,以便能够告诉编译器路径表示目录

let folderName = "MyNewFolder"
let folderURL = URL.documentsDirectory.appending(path: folderName, directoryHint: .isDirectory)
let folderExists = (try? folderURL.checkResourceIsReachable()) ?? false
do {
    if !folderExists {
        try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: false)
    }
    let fileURL = folderURL.appendingPathComponent("log.txt")
    let hello = Data("hello".utf8)
    try hello.write(to: fileURL)
    
} catch { print(error) }
dl5txlt9

dl5txlt92#

你可以尝试

try? FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: false, attributes: nil)

do { 

    let sto =  URL(fileURLWithPath: dataPath + "log.txt")  // or let sto =  URL(fileURLWithPath: dataPath + "/log.txt") 

    try Data("SomeValue".utf8).write(to: sto)

    let read = try Data(contentsOf: sto)

    print(String(data: read, encoding: .utf8)!)
}
catch {

    print(error)
}
rm5edbpk

rm5edbpk3#

let filePath = dataPath + "/log.txt"
FileManager.default.createFile(filePath, contents:dataWithFileContents, attributes:nil)

相关问题