Swift文件与IO操作

发布于:2024-04-20 ⋅ 阅读:(21) ⋅ 点赞:(0)

在Swift中,我们可以通过文件路径或URL进行文件的读写操作。文件路径是文件在文件系统中的位置,可以是绝对路径或相对路径。URL是统一资源定位符,可以指向本地文件或远程资源。

  1. 从文件路径或URL获取文件内容:
    let filePath = "/path/to/file.txt"
    
    if let content = try? String(contentsOfFile: filePath) {
        print(content)
    } else {
        print("Failed to read the file.")
    }
    
    let fileURL = URL(fileURLWithPath: filePath)
    
    do {
        let content = try String(contentsOf: fileURL)
        print(content)
    } catch {
        print("Failed to read the file.")
    }
    

  2. 写入文件:
    let content = "Hello, World!"
    
    let filePath = "/path/to/file.txt"
    do {
        try content.write(toFile: filePath, atomically: true, encoding: .utf8)
        print("File written successfully.")
    } catch {
        print("Failed to write to the file.")
    }
    
    let fileURL = URL(fileURLWithPath: filePath)
    do {
        try content.write(to: fileURL, atomically: true, encoding: .utf8)
        print("File written successfully.")
    } catch {
        print("Failed to write to the file.")
    }
    

  3. 序列化与反序列化:
    struct Person: Codable {
        let name: String
        let age: Int
    }
    
    let person = Person(name: "John", age: 30)
    
    // 序列化为JSON数据
    do {
        let jsonData = try JSONEncoder().encode(person)
        // 写入文件
        let filePath = "/path/to/person.json"
        try jsonData.write(to: URL(fileURLWithPath: filePath))
        print("JSON data written successfully.")
    } catch {
        print("Failed to serialize the object.")
    }
    
    // 反序列化为对象
    let fileURL = URL(fileURLWithPath: filePath)
    do {
        let jsonData = try Data(contentsOf: fileURL)
        let decodedPerson = try JSONDecoder().decode(Person.self, from: jsonData)
        print(decodedPerson)
    } catch {
        print("Failed to deserialize the object.")
    }
    

总结:通过文件路径或URL,我们可以实现文件的读写操作。同时,通过序列化与反序列化,我们可以将对象转化为数据,并存储到文件中,或者从文件中读取数据并转化为对象。这些操作都需要进行错误处理,以防止出现异常情况。