在Swift中逐行读取文本文件?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在Swift中逐行读取文本文件?相关的知识,希望对你有一定的参考价值。
刚开始学习Swift,我已经从文本文件中读取了代码,应用程序显示了整个文本文件的内容。如何逐行显示并多次调用该行?
TextFile.txt包含以下内容。
- 香蕉
- 苹果
- 梨
- 草莓
- 蓝莓
- 黑醋栗
以下是目前的......
if let path = NSBundle.mainBundle().pathForResource("TextFile", ofType: "txt"){
var data = String(contentsOfFile:path, encoding: NSUTF8StringEncoding, error: nil)
if let content = (data){
TextView.text = content
}
如果还有其他方式,请告诉我。非常感激
答案
Swift 3.0
if let path = Bundle.main.path(forResource: "TextFile", ofType: "txt") {
do {
let data = try String(contentsOfFile: path, encoding: .utf8)
let myStrings = data.components(separatedBy: .newlines)
TextView.text = myStrings.joined(separator: ", ")
} catch {
print(error)
}
}
变量myStrings
应该是数据的每一行。
使用的代码来自:用Obj-C编写的Reading file line by line in iOS SDK并使用NSString
检查以前版本的Swift的编辑历史记录。
另一答案
更新Swift 2.0 / Xcode 7.2
do {
if let path = NSBundle.mainBundle().pathForResource("TextFile", ofType: "txt"){
let data = try String(contentsOfFile:path, encoding: NSUTF8StringEncoding)
let myStrings = data.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
print(myStrings)
}
} catch let err as NSError {
//do sth with Error
print(err)
}
另外值得一提的是,此代码读取项目文件夹中的文件(因为使用了pathForResource),而不是例如设备的文件夹
另一答案
在Swift 5.0中执行此操作的最简单,最简单的方法可能如下:
import Foundation
// Determine the file name
let filename = "main.swift"
// Read the contents of the specified file
let contents = try! String(contentsOfFile: filename)
// Split the file into separate lines
let lines = contents.split(separator:"
")
// Iterate over each line and print the line
for line in lines {
print("(line)")
}
归功于:https://wiki.codermerlin.com/mediawiki/index.php/Code_Snippet:_Print_a_File_Line-by-Line
另一答案
您可能确实希望立即读取整个文件。我打赌它很小。
但是,您希望将生成的字符串拆分为数组,然后在各种UI元素(如表格单元格)之间分发数组的内容。
一个简单的例子:
var x: String = "abc
def"
var y = x.componentsSeparatedByString("
")
// y is now a [String]: ["abc", "def"]
另一答案
这不是很好,但我相信它有效(在Swift 5上)。这使用底层POSIX getline
命令进行迭代和文件读取。
typealias LineState = (
// pointer to a C string representing a line
linePtr:UnsafeMutablePointer<CChar>?,
linecap:Int,
filePtr:UnsafeMutablePointer<FILE>?
)
/// Returns a sequence which iterates through all lines of the the file at the URL.
///
/// - Parameter url: file URL of a file to read
/// - Returns: a Sequence which lazily iterates through lines of the file
///
/// - warning: the caller of this function **must** iterate through all lines of the file, since aborting iteration midway will leak memory and a file pointer
/// - precondition: the file must be UTF8-encoded (which includes, ASCII-encoded)
func lines(ofFile url:URL) -> UnfoldSequence<String,LineState>
{
let initialState:LineState = (linePtr:nil, linecap:0, filePtr:fopen(fileURL.path,"r"))
return sequence(state: initialState, next: { (state) -> String? in
if getline(&state.linePtr, &state.linecap, state.filePtr) > 0,
let theLine = state.linePtr {
return String.init(cString:theLine)
}
else {
if let actualLine = state.linePtr { free(actualLine) }
fclose(state.filePtr)
return nil
}
})
}
以下是您可以使用它的方法:
for line in lines(ofFile:myFileURL) {
print(line)
}
以上是关于在Swift中逐行读取文本文件?的主要内容,如果未能解决你的问题,请参考以下文章