使用数组 Swift 5 Xcode iOS 替换文本文件中的特定行 [英] Replace a specific line in a text file using an array Swift 5 Xcode iOS

查看:44
本文介绍了使用数组 Swift 5 Xcode iOS 替换文本文件中的特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm converting my app from Java Android to Swift 5 iOS.

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

I cannot seem to find anything that points to what I am looking for.

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

Essentially I have an array that I load my file into. I use this in order to access the specific line that needs to be replaced. The only thing I cannot seem to get is to load the array back to the file. (essentially replacing the contents of the file with the contents of the array).

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

I understand I may need to do something to convert the array back but unsure if this is the best method.

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 实现了这一点:

I achieved this in Java with:

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

如果需要更多信息.让我知道

If further information is required. Let me know

推荐答案

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

I recommend to use a more efficient way to find the line starting with iD plus comma. And according to the code the 7th field is bagged and the 8th field is baggedDate.

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

So write the changes directly into the attributes array, rejoin it, reassign the string to the lines array at given index and join the lines array with CRLF separator. Finally write the string back to disk

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)}
}

这篇关于使用数组 Swift 5 Xcode iOS 替换文本文件中的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆