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

时间:2021-09-23 05:47:00

I've been looking all over the Internet for an answer to this one, and every answer I've gotten either hasn't worked, is enormously complex, is for iOS only, or a combination of the three. I am just looking for a simple way to perform file I/O in Swift for use on a Mac. So I guess that a way to mix c++ and swift would also work, but for that I've had the same problems as before. Any help would be greatly appreciated!

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

2 个解决方案

#1


11  

There are many options, it depends what you're trying to write and also the size/etc of the data (hundreds of megabytes of data requires different techniques).

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

But the simplest method is:

但最简单的方法是:

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)

One thing that might be catching you out is OS X has strict sandboxing to prevent which parts of the disk you can write to. As a security measure for users pasting random code into Xcode and to prevent bugs erasing somebody's entire hard drive... the Playground enforces the sandbox although many mac apps do not use sandboxing (it's usually only enabled for apps deployed in Apple's store).

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

Your app has a sandbox on the disk that you can write to, this is what NSFileManager() is returning URL for above.

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

To punch a hole in the sandbox to the rest of the disk, you need to involve the user. Eg if they drag a file onto your app icon, you can write to it. If they select a file in an open or save panel then you can write to that. If the user selects a directory, or even the root of the file system, you can write to the all descendants of the selection.

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

It's also possible to persist access to a file/directory across app launches, although I've never looked into how that works. NSDocumentController does it for you, if you use that for a document based app.

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

#2


7  

Abhi Beckert's code updated to Swift 3:

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)

#1


11  

There are many options, it depends what you're trying to write and also the size/etc of the data (hundreds of megabytes of data requires different techniques).

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

But the simplest method is:

但最简单的方法是:

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)

One thing that might be catching you out is OS X has strict sandboxing to prevent which parts of the disk you can write to. As a security measure for users pasting random code into Xcode and to prevent bugs erasing somebody's entire hard drive... the Playground enforces the sandbox although many mac apps do not use sandboxing (it's usually only enabled for apps deployed in Apple's store).

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

Your app has a sandbox on the disk that you can write to, this is what NSFileManager() is returning URL for above.

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

To punch a hole in the sandbox to the rest of the disk, you need to involve the user. Eg if they drag a file onto your app icon, you can write to it. If they select a file in an open or save panel then you can write to that. If the user selects a directory, or even the root of the file system, you can write to the all descendants of the selection.

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

It's also possible to persist access to a file/directory across app launches, although I've never looked into how that works. NSDocumentController does it for you, if you use that for a document based app.

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

#2


7  

Abhi Beckert's code updated to Swift 3:

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)