如何使用Swift逐行将文本文件加载到数组中?

时间:2014-06-04 14:26:05

标签: ios swift

如何使用array逐行将文本文件加载到swift

9 个答案:

答案 0 :(得分:60)

有些事情:

func arrayFromContentsOfFileWithName(fileName: String) -> [String]? {
    guard let path = NSBundle.mainBundle().pathForResource(fileName, ofType: "txt") else {
        return nil
    }

    do {
        let content = try String(contentsOfFile:path, encoding: NSUTF8StringEncoding)
        return content.componentsSeparatedByString("\n")
    } catch _ as NSError {
        return nil
    }
}

此方法假定相关文件位于您的应用包中。

答案 1 :(得分:6)

这只适用于Xcode 6.1 beta 1.在6.1 beta 2中你必须写下:

var err: NSError? = NSError()
let s = String(contentsOfFile: fullPath, encoding: NSUTF8StringEncoding, error: &err)

其中fullPath是包含文件完整路径的字符串,而NSUTF8StringEncoding是UTF8编码的预定义常量。

您还可以将NSMacOSRomanStringEncoding用于Mac文件,或NSISOLatin1StringEncoding用于Windows文件。

s是一个可选字符串,您可以查看读取文件是否成功:

if (s != nil)
{
    return (s!) // Return the string as "normal" string, not as optional string
}

答案 2 :(得分:6)

基于接受的答案的Swift 3版本:

func arrayFromContentsOfFileWithName(fileName: String) -> [String]? {
    guard let path = Bundle.main.path(forResource: fileName, ofType: "txt") else {
        return nil
    }

    do {
        let content = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
        return content.components(separatedBy: "\n")
    } catch {
        return nil
    }
}

答案 3 :(得分:5)

如果您使用的是Swift 2.0,则应使用:

let path = NSBundle.mainBundle().pathForResource(fileName, ofType: nil)
if path == nil {
  return nil
}

var fileContents: String? = nil
do {
  fileContents = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
} catch _ as NSError {
  return nil
}

答案 4 :(得分:2)

我的简单编码

 let path = NSBundle.mainBundle().pathForResource("FileName", ofType: "txt")
 var text = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!
 println(text)
 var array = text.componentsSeparatedByString("\n")

答案 5 :(得分:2)

使用Swift 5,根据您的需要,您可以选择以下3种方法之一来解决您的问题。

#1。使用StringProtocol components(separatedBy:)方法和CharacterSet参数

FoundationString提供了一个名为components(separatedBy:)的方法,其声明如下:

func components(separatedBy separator: CharacterSet) -> [String]
  

返回一个数组,其中包含字符串中的子字符串,这些子字符串已被给定集合中的字符除以。

下面的代码示例显示如何将components(separatedBy:)的参数设置为CharacterSet.newlines,以便逐行将文本文件的内容加载到数组中:

let path = Bundle.main.path(forResource: "Lorem Ipsum", ofType: "txt")!
let text = try! String(contentsOfFile: path, encoding: String.Encoding.utf8)
let lines = text.components(separatedBy: CharacterSet.newlines)

print(lines)

#2。使用StringProtocol components(separatedBy:)方法和String参数

FoundationString提供了一个名为components(separatedBy:)的方法,该方法采用String类型的参数。 components(separatedBy:)有以下声明:

func components<T>(separatedBy separator: T) -> [String] where T : StringProtocol

下面的代码示例显示了如何使用components(separatedBy:)将文本文件的内容逐行加载到数组中:

let path = Bundle.main.path(forResource: "Lorem Ipsum", ofType: "txt")!
let text = try! String(contentsOfFile: path, encoding: String.Encoding.utf8)
let lines = text.components(separatedBy: "\n")

print(lines)

⚠️您应该更喜欢带components(separatedBy:)参数的CharacterSet重载并将其与值CharacterSet.newlines一起使用,因为这将管理所有换行符(U + 000A~U + 000D) ,U + 0085,U + 2028和U + 2029)。

#3。使用StringProtocol&#39; enumerateSubstrings(in:options:_:)方法

FoundationString提供了一个名为enumerateSubstrings(in:options:_:)的方法。下面的代码示例显示如何将enumerateSubstrings(in:options:_:) options参数值设置为String.EnumerationOptions.byLines,以便将文本文件的内容逐行加载到数组中:

let path = Bundle.main.path(forResource: "Lorem Ipsum", ofType: "txt")!
let text = try! String(contentsOfFile: path, encoding: String.Encoding.utf8)

let range = text.startIndex ..< text.endIndex
var lines = [String]()
text.enumerateSubstrings(in: range, options: String.EnumerationOptions.byLines) {
    (substring, range, enclosingRange, stop) in
    guard let substring = substring else { return }
    lines.append(substring)
}

print(lines)

答案 6 :(得分:1)

Swift 3.0

if let path = Bundle.main.path(forResource: <#FileName#>, ofType: "txt")
{
    do
    {
        let str = try String(contentsOfFile:path, encoding: String.Encoding.utf8)
        return str.components(separatedBy: "\n")
    }
    catch
    {

    }
}
else
{
    return nil
}

答案 7 :(得分:0)

对我来说,作品如下:

{
  test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
  loader: "url?limit=10000&mimetype=application/font-woff&name=./javascripts/[hash].[ext]"
}, {
  test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
  loader: "url?limit=10000&mimetype=application/font-woff&name=./javascripts/[hash].[ext]"
}, {
  test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
  loader: "url?limit=10000&mimetype=application/octet-stream&name=./javascripts/[hash].[ext]"
}, {
  test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
  loader: "file?name=./javascripts/[hash].[ext]"
}, {
  test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
  loader: "url?limit=10000&mimetype=image/svg+xml&name=./javascripts/[hash].[ext]"
}

答案 8 :(得分:0)

如果要读取数字数据的csv文件。 (根据Cezar的回答)

func get_csv_data() -> [[Double]] {
    guard let path = NSBundle.mainBundle().pathForResource("filename_without_extension", ofType: "csv") else {
        return []
    }
    do {
        let content = try String(contentsOfFile:path, encoding: NSUTF8StringEncoding)
        let line_str_array = content.componentsSeparatedByString("\n")
        return line_str_array.map {
            let field_str_array = $0.componentsSeparatedByString(",")
            return field_str_array.map {
                Double($0)!
            }
        }
    } catch _ as NSError {
        return []
    }
}