swift - 如何在 Swift 4 中逐行写入文件

标签 swift

我需要帮助弄清楚如何重复写入同一个打开的输出文件。 我正在使用 Swift 4.2。我的搜索和测试只发现了将单个文本字符串写入文件然后关闭该文件的代码。下一个空位会覆盖上一个空位。一个例子如下所示。

问题是我需要能够写入大量记录(例如 150 万条),并在将每条记录写入文件之前对其执行计算。当代码在关闭之前只写入一次时,这是不可行的。我将其称为“逐行写入”,与“逐行读取”非常相似。

我试图在各种 Swift write 语句和 SO 帖子中找到一个选项,但一切似乎都是为了编写一次然后关闭文件。我尝试了打开追加,但这不起作用,而且每次我想写入文件时打开、关闭、重新追加似乎效率很低。我在 Swift 中尝试了一些 C 代码,使用 open(... 和 freopen(... 但无法得到编译器不会提示的东西。希望有一种方法可以在 Swift 中完成这一切。以下代码可以很好地工作写。

let file0 = “test_file.txt”
let s0 = ("This is a test line of text")
do {
  try s0.write(to: NSURL(fileURLWithPath: file0) as URL, atomically: false, encoding: String.Encoding.utf8)
} catch {
  print("Problem writing to file0")
}

如何调整此代码片段以写入一个字符串,然后再写入另一个字符串,然后在全部完成后关闭文件之前?如果没有这个,是否有 Swift 代码可以完成这项工作?

最佳答案

以下是在 Swift 中逐行写入文件所需的基本代码组件。首先是一些文件管理代码,如果文件不存在则创建该文件,然后是打印一系列示例语句的代码,然后是循环打印到文件的代码,最后关闭文件。这段代码在 Swift 4.2 中可以正常工作。这个和问题中的方法的区别在于,这段代码中的write语句使用了fileHandle的方法!问题展示了 Swift 字符串的方法。

print("Swift_Write_to_File_Test_1")

var outFilename: NSString = "test_file.txt"

// Begin file manager segment
// Check for file presence and create it if it does not exist
let filemgr = FileManager.default
let path = filemgr.urls(for: FileManager.SearchPathDirectory.documentDirectory, in:     FileManager.SearchPathDomainMask.userDomainMask).last?.appendingPathComponent(outFilename as String)
if !filemgr.fileExists(atPath: (path?.absoluteString)!) {
filemgr.createFile(atPath: String(outFilename),  contents:Data(" ".utf8), attributes: nil)
}
// End file manager Segment

// Open outFilename for writing – this does not create a file
let fileHandle = FileHandle(forWritingAtPath: outFilename as String)

if(fileHandle == nil)
{
print("Open of outFilename forWritingAtPath: failed.  \nCheck whether the file already exists.  \nIt should already exist.\n");
exit(0)
}

var str: NSString = "2. Test string from NSString.\n";
var str0: String = "3. Test string from a Swift String.\n"
var str1: NSString = "4. Test string from NSString.\n";

fileHandle!.write("1. Text String in-line with code statement.\n".data(using: .utf8)!)
fileHandle!.write(String(str).data(using: .utf8)!)
fileHandle!.write(str0.data(using: .utf8)!)
fileHandle!.write(String(str1).data(using: .utf8)!)
fileHandle!.write("5. Text String in-line with code statement.\n".data(using: .utf8)!)
fileHandle!.write("6. Text in a loop follows: \n".data(using: .utf8)!)
for i in 0...5
{
    //Assemble a string then write it to the file.
    var s0: String = ""
    s0 = String(i)
    //s0.append("  ... some text here.\n") // See improvement below
    s0 += "  ... some text here.\n" // This is a better than .append 
    fileHandle!.write(s0.data(using: .utf8)!)
}
// End of file-writing segment 


fileHandle!.closeFile()

关于swift - 如何在 Swift 4 中逐行写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58107752/

相关文章:

swift - Swift 中的对齐与步幅

swift - 准备 segue.. 从 UITableView 到 DetailView 解析对象

ios - GMSMapView(谷歌地图)上的按钮使用 Swift

swift - 在登录时启动 OS X 应用程序

arrays - Swift:在扩展中声明一个类型的数组符合协议(protocol)

ios - 当 imageview 在里面时,Swift CollectionView 会改变大小

ios - Swift - 从 map 注释执行 Segue

swift - 统一的 Swift API : use of undeclared type T

swift - 在 Swift 中打印奇数个数

swift - 如何在 Swift 中限制 UITextField 中的某些字符?