如何在mac上使用Swift读取和写入文件?

Ste*_*all 10 macos file-io swift

我一直在互联网上寻找这个问题的答案,而且我得到的每一个答案都没有用,非常复杂,仅适用于iOS,或者是三者的组合.我只是在寻找一种在Swift中执行文件I/O以便在Mac上使用的简单方法.所以我想混合c ++和swift的方法也可以,但是为此我遇到了和以前一样的问题.任何帮助将不胜感激!

Abh*_*ert 12

有很多选择,它取决于您要编写的内容以及数据的大小/等(数百兆字节的数据需要不同的技术).

但最简单的方法是:

import Cocoa

var str = "Hello, playground"

// get URL to the the documents directory in the sandbox
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL

// add a filename
let fileUrl = documentsUrl.URLByAppendingPathComponent("foo.txt")

// write to it
str.writeToURL(fileUrl, atomically: true, encoding: NSUTF8StringEncoding, error: nil)
Run Code Online (Sandbox Code Playgroud)

有一件事可能会让你感到困惑的是OS X有严格的沙盒来防止你可以写入磁盘的哪些部分.作为一种安全措施,用户将随机代码粘贴到Xcode中并防止错误消除某人的整个硬盘驱动器......尽管许多mac应用程序不使用沙盒(但通常只对Apple商店中部署的应用程序启用),Playground会强制执行沙箱.

您的应用程序在磁盘上有一个可以写入的沙箱,这就是NSFileManager()返回上面的URL.

要将沙箱中的孔打到磁盘的其余部分,您需要让用户参与进来.例如,如果他们将文件拖到您的应用程序图标上,您可以写入它.如果他们在打开或保存面板中选择文件,那么您可以写入该文件.如果用户选择目录,甚至是文件系统的根目录,则可以写入选择的所有后代.

也可以在应用程序启动期间持久访问文件/目录,尽管我从未研究过它是如何工作的.NSDocumentController为您完成,如果您将其用于基于文档的应用程序.


tea*_*cup 12

Abhi Beckert的代码更新为Swift 3:

import Cocoa

var str = "Hello, playground"

// get URL to the the documents directory in the sandbox
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as NSURL

// add a filename
let fileUrl = documentsUrl.appendingPathComponent("foo.txt")

// write to it
try! str.write(to: fileUrl!, atomically: true, encoding: String.Encoding.utf8)
Run Code Online (Sandbox Code Playgroud)