ios 在 Swift 中逐行读取文本文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31778700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read a text file line by line in Swift?
提问by ScarletEnvy
Just started learning Swift, I have got my code to read from the text file, and the App displays the content of the Entire Text file. How can I display line by line and call upon that line multiple times?
刚开始学习 Swift,我已经从文本文件中读取了我的代码,应用程序显示了整个文本文件的内容。如何逐行显示并多次调用该行?
TextFile.txt contains the following.
TextFile.txt 包含以下内容。
- Banana
- Apple
- pear
- strawberry
- blueberry
- blackcurrent
- 香蕉
- 苹果
- 梨
- 草莓
- 蓝莓
- 黑流
the following is what currently have..
以下是目前有..
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
}
also if there is another way, of doing this please let me know. Much appreciated
另外,如果有另一种方式,请让我知道。非常感激
回答by Caleb
Swift 3.0
斯威夫特 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)
}
}
The variable myStrings
should be each line of the data.
变量myStrings
应该是数据的每一行。
The code used is from: Reading file line by line in iOS SDKwritten in Obj-C and using NSString
使用的代码来自: Reading file line by line in iOS SDKwrite in Obj-C and using NSString
Check edit history for previous versions of Swift.
检查以前版本的 Swift 的编辑历史记录。
回答by glace
Update for Swift 2.0 / Xcode 7.2
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)
}
Also worth to mention is that this code reads a file which is in the project folder (since pathForResource is used), and not in e.g. the documents folder of the device
另外值得一提的是,这段代码读取了一个位于项目文件夹中的文件(因为使用了 pathForResource),而不是在设备的文档文件夹中
回答by algal
This is not pretty, but I believe it works (on Swift 5). This uses the underlying POSIX getline
command for iteration and file reading.
这并不漂亮,但我相信它有效(在 Swift 5 上)。这使用底层 POSIXgetline
命令进行迭代和文件读取。
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
}
})
}
Here is how you might use it:
以下是您可以如何使用它:
for line in lines(ofFile:myFileURL) {
print(line)
}
回答by NerdOfCode
Probably the simplest, and easiest way to do this in Swift 5.0, would be the following:
在 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:"\n")
// Iterate over each line and print the line
for line in lines {
print("\(line)")
}
Note: This reads the entire file into memory, and then just iterates over the file in memory to produce lines....
注意:这将整个文件读入内存,然后只是迭代内存中的文件以生成行....
Credit goes to: https://wiki.codermerlin.com/mediawiki/index.php/Code_Snippet:_Print_a_File_Line-by-Line
归功于:https: //wiki.codermerlin.com/mediawiki/index.php/Code_Snippet: _Print_a_File_Line-by-Line
回答by BaseZen
You probably do want to read the entire file in at once. I bet it's very small.
您可能希望一次读取整个文件。我敢打赌它很小。
But then you want to split the resulting string into an array, and then distribute the array's contents among various UI elements, such as table cells.
但是随后您想将结果字符串拆分为一个数组,然后将数组的内容分布在各种 UI 元素(例如表格单元格)中。
A simple example:
一个简单的例子:
var x: String = "abc\ndef"
var y = x.componentsSeparatedByString("\n")
// y is now a [String]: ["abc", "def"]