如何从特定路径读取文件

时间:2018-03-15 13:14:31

标签: ios swift file

我正在尝试从路径中读取和写入文件(例如:“/ Desktop / folder”)。如果无法做到这一点,那么从Documents(例如:“/ Documents / folder”)。我看到并尝试了几个示例,但问题是该文件位于以下位置:

  

文件:///用户/名称/库/开发商/ CoreSimulator /设备/ AE6A47DE-D6D0-49AE-B39F-25C7A2335DC8 /数据/容器/数据/应用/ 09F890C1-081F-46E7-88BC-F8453BAFC1CB /文档/的test.txt”   0x00006000000af780

即使我在Documents中甚至在项目中都有“Test.txt”。

以下是在上述位置读取和写入文件的代码:

 let file = "Test.txt" //this is the file. we will write to and read from it

    let text = "some text" //just a text

    var text2 = ""

    if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

        let fileURL = dir.appendingPathComponent(file)

        //writing
        do {
            try text.write(to: fileURL, atomically: false, encoding: .utf8)
        }
        catch {/* error handling here */print(error)}

        //reading
        do {
             text2 = try String(contentsOf: fileURL, encoding: .utf8)
        }
        catch {/* error handling here */ print(error)}
    }

是否可以从我需要的路径读取和写入文件(例如:“Documents / Folder”)?

2 个答案:

答案 0 :(得分:1)

所以,就像你现在一样,拿走文件目录,然后追加你需要的路径:

let file = "Test.txt" //this is the file. we will write to and read from it

guard let dir = FileManager.default.urls(for: .documentDirectory, 
  in: .userDomainMask).first { else return }

let subDir = dir.appendingPathComponent("Folder", isDirectory: true)
let fileURL = subDir.appendingPathComponent(file)

请注意,如果子文件夹"文件夹"尝试写入该文件URL将失败。不存在。您必须使用其中一个文件管理器createDirectory调用来创建"文件夹"目录,如果它不存在。

答案 1 :(得分:0)

我找到了解决方案:

  let file = "Test.txt" //this is the file. we will write to and read from it
            let text = "some text" //just a text
            var text2 = ""

            let fileURL = URL(fileURLWithPath: "/Users/name/Documents/Folder/Test.txt")
                //writing
                do {
                    try text.write(to: fileURL, atomically: false, encoding: .utf8)
                }
                catch {/* error handling here */print(error)}
                //reading
                do {
                    text2 = try String(contentsOf: fileURL, encoding: .utf8)
                    var s = ""
                }
                catch {/* error handling here */ print(error)}
            }