【发布时间】: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