使用 Swift 读取本地文件的简单方法? [英] Simple way to read local file using Swift?

查看:49
本文介绍了使用 Swift 读取本地文件的简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力学习新的 Swift 编程语言.看起来不错,但我很难做一些像读取本地 .txt 文件的内容这样简单的事情.

I'm trying to learn the new Swift programming language. It looks great, but I'm having a difficult time doing something as simple as reading the content of a local .txt file.

我已经尝试了通过 Google 找到的几个例子,但它们给出了编译错误,就像这里的答案:从文本文件读取和写入数据如果我稍微调整一下代码,它就可以工作,但只能从项目中的特殊位置读取.

I have tried the few examples I could find through Google, but they give compile errors, like this answer here: Read and write data from text file If I tweak the code a bit, it works, but can only read from a special location within the project.

为什么使用 Swift 读取 .txt 文件不像使用 Ruby 那样简单?我将如何读取位于 ~/file.txt 的文件的内容?

Why isn't it just as simple to read a .txt file with Swift as it is with for instance Ruby? And how would I go about reading the content of a file located at ~/file.txt?

谢谢

推荐答案

如果你的路径中有波浪号,你可以试试这个:

If you have a tilde in your path you can try this:

let location = "~/file.txt".stringByExpandingTildeInPath
let fileContent = NSString(contentsOfFile: location, encoding: NSUTF8StringEncoding, error: nil)

否则就用这个:

let location = "/Users/you/Desktop/test.txt"
let fileContent = NSString(contentsOfFile: location, encoding: NSUTF8StringEncoding, error: nil)

这为您提供了文件的字符串表示形式,我认为这是您想要的.您可以使用 NSData(contentsOfFile: location) 来获取二进制表示,但您通常会为音乐文件而不是文本文件执行此操作.

This gives you a string representation of the file, which I assumed is what you want. You can use NSData(contentsOfFile: location) to get a binary representation, but you would normally do that for, say, music files and not a text file.


更新:使用 Xcode 7 和 Swift 2,这不再起作用.您现在可以使用

let location = NSString(string:"~/file.txt").stringByExpandingTildeInPath
let fileContent = try? NSString(contentsOfFile: location, encoding: NSUTF8StringEncoding)

这篇关于使用 Swift 读取本地文件的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆