Dan Sali
Dan Sali

Reputation: 1

How to read a file from certain path

I'm trying to read and write a file from a path (ex: "/Desktop/folder"). If this can't be done, then from Documents (ex: "/Documents/folder"). I saw and tried several examples, but the problem is that the file is located in a location such:

file:///Users/name/Library/Developer/CoreSimulator/Devices/AE6A47DE-D6D0-49AE-B39F-25C7A2335DC8/data/Containers/Data/Application/09F890C1-081F-46E7-88BC-F8453BAFC1CB/Documents/Test.txt" 0x00006000000af780

Even if i have the "Test.txt" in Documents and even in project.

Here's the code which reads and writes a file at the above location:

 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)}
    }

Is it possible to read and write file from path i need (ex: "Documents/Folder")?

Upvotes: 0

Views: 102

Answers (2)

Dan Sali
Dan Sali

Reputation: 1

I find the solution:

  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)}
            }

Upvotes: 0

Duncan C
Duncan C

Reputation: 131416

So, like you're doing now, take the documents dir, and append the path you need:

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)

Note that trying to write to that file URL will fail if the sub-folder "Folder" doesn't already exist. You'd have to use one of the file manager createDirectory calls to create the "Folder" directory if it doesn't exist.

Upvotes: 1

Related Questions