【问题标题】:Replace a specific line in a text file using an array Swift 5 Xcode iOS使用数组Swift 5 Xcode iOS替换文本文件中的特定行
【发布时间】:2020-02-26 21:17:10
【问题描述】:

我正在将我的应用从 Java Android 转换为 Swift 5 iOS。

我似乎找不到任何指向我正在寻找的东西。

基本上,我有一个将文件加载到其中的数组。我使用它来访问需要替换的特定行。我似乎唯一无法得到的是将数组加载回文件。 (本质上是用数组的内容替换文件的内容)。

我知道我可能需要做一些事情来将数组转换回来,但不确定这是否是最好的方法。

func saveToFile(bagged: Int, iD: Int, dateBagged: Date){
        var arrayOfLines: [String]?

        let dateFormat = "dd-MMM-yyyy";
        let dateFormatter = DateFormatter();
        dateFormatter.dateFormat = dateFormat;

        let dateBaggedFormatted = dateFormatter.string(from: dateBagged)

        do {
            let file = "file.txt"

            if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

                let fileURL = dir.appendingPathComponent(file)

                let data = try String(contentsOf:fileURL, encoding: String.Encoding.utf8)

                arrayOfLineStrings = data.components(separatedBy: "\r\n")


                for i in 0 ..< arrayOfLines!.count {
                    let attributes: [String] =  arrayOfLines![i].components(separatedBy: ",");
                    if (attributes[0] == String(iD)) {
                        let replaceLine: String = attributes[0] + "," +
                            attributes[1] + "," +
                            attributes[2] + "," +
                            attributes[3] + "," +
                            attributes[4] + "," +
                            attributes[5] + "," +
                            String(bagged) + "," +
                        dateBaggedFormatted;
                        arrayOfLines![i]=replaceLine
                        break;
                    }
                }

//                let contents = try! String(contentsOf: fileURL)
//                let lines = contents.split(separator:"\r\n")
//                
//                for line in lines {
//                    try line.write(to: fileURL, atomically: false, encoding: .utf8)
//                }
            }
        }
        catch {/* error handling here */}
    }

我用 Java 实现了这一点:

Files.write(Paths.get(outFile.getAbsolutePath()), fileContent, StandardCharsets.UTF_8); (I understand that will probably not help at all...)

如果需要更多信息。告诉我

【问题讨论】:

  • 不清楚写一个行数组意味着什么。基本上你应该加入行数组来形成一个字符串;现在你只需编写字符串。

标签: ios swift xcode text-files writing


【解决方案1】:

如你所说,将字符串写入文件的方法是

try? myString.write(to: fileURL, atomically: true, encoding: .utf8)

所以如果arrayOfLines[String],你可以说

try? arrayOfLines.joined(separator: "\n").write(to:...)

【讨论】:

  • 忍者超过两分钟!一件小事:他被"\r\n"分开,所以这可能就是加入的确切事情。
  • 就像我说的,如果需要任何澄清,我很乐意补充。我在发布后找到了加入的方法,非常感谢你的回答。谢谢您的帮助。这个社区在回答问题时似乎更加苛刻......
  • 完全是@Tommy。您的评论帮助我记住了添加!
【解决方案2】:

我建议使用更有效的方法来查找以iD plus comma 开头的行。根据代码,第 7 个字段是 bagged,第 8 个字段是 baggedDate

因此,将更改直接写入attributes 数组,重新加入它,将字符串重新分配给给定索引处的lines 数组,并使用CRLF 分隔符加入lines 数组。最后将字符串写回磁盘

func saveToFile(bagged: Int, iD: Int, dateBagged: Date){
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd-MMM-yyyy"

    let dateBaggedFormatted = dateFormatter.string(from: dateBagged)

    do {
        let file = "file.txt"

        let dir = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)

        let fileURL = dir.appendingPathComponent(file)

        let text = try String(contentsOf: fileURL, encoding: .utf8)
        var lines = text.components(separatedBy: .newlines)
        if let index = lines.firstIndex(where: {$0.hasPrefix("\(iD),")}) {
            var attributes = lines[index].components(separatedBy: ",")
            attributes[6] = String(bagged)
            attributes[7] = dateBaggedFormatted
            lines[index] = attributes.joined(separator: ",")
            let result = lines.joined(separator: "\r\n")
            try result.write(to: fileURL, atomically: true, encoding: .utf8)
        }
    } catch {print(error)}
}

【讨论】:

  • 我真的很欣赏这种更简洁的逻辑。尽管它似乎在每行之后添加了一个额外的空字符串。我会努力删除它!
  • 我已将 separatorBy: .newlines 更改为 separatorBy: "\r\n"。这对我帮助很大。祝你有个愉快的夜晚。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-10
  • 2019-03-02
  • 1970-01-01
相关资源
最近更新 更多