在 Swift 中读取文本文件 [英] Read text file in Swift

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

问题描述

我试图从程序中读取一个文本文件,这是

I am trying to read a text file from the program, which is

 var name = String.stringWithContentsOfFile("test.txt", encoding: NSUTF8StringEncoding, error:nil)

(其中 text.txt 在项目文件夹下)

(where text.txt is under project folder)

我也试过:

 var name = String.stringWithContentsOfFile("/Users/Michael/Desktop/test.txt", encoding: NSUTF8StringEncoding, error:nil)

(目录)

他们都向我返回一个 nil 值.我检查了该文件并确保它是一个带有 UTF-8 代码的 txt 文件.有人可以帮我吗?

And both of them return a nil value to me. I checked the file and make sure it is a txt file with UTF-8 code. Can someone help me?

推荐答案

您遇到了这个问题,因为您已将文件路径指定为字符串,而它应该是路径对象.试试下面的例子:

You have that problem, because you've specified the path to the file as a string, while it should be a path object. Try the following example:

let path = NSBundle.mainBundle().pathForResource("fileName", ofType: "txt")
var data = String.stringWithContentsOfFile(path, encoding: NSUTF8StringEncoding, error: nil)

此示例假设相关文件位于您的应用程序包中.

This example assumes that the file in question is located in your app bundle.

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

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