我有两个文件,File1和File2。我想在File1的末尾附加File2。
func writeToFile(content: String, fileName: String) {
let contentToAppend = content+"\n"
let filePath = NSHomeDirectory() + "/Documents/" + fileName
//Check if file exists
if let fileHandle = FileHandle(forWritingAtPath: filePath) {
//Append to file
fileHandle.seekToEndOfFile()
fileHandle.write(contentToAppend.data(using: String.Encoding.utf8)!)
}
else {
//Create new file
do {
try contentToAppend.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8)
} catch {
print("Error creating \(filePath)")
}
}
}
我正在使用此功能在文件末尾添加字符串。我没有找到任何要追加文件的末尾。如果我错过了什么,任何人都可以在这里帮助我。
答案 0 :(得分:1)
正如rmaddy所说,您使用错误的代码来获取文档目录。为此,您应该使用类似以下的代码:
guard let docsURL = try? FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true else { return }
然后,您需要代码来读取要附加的文件,并使用write附加它:
let fileURL = docsURL.appendingPathComponent(fileName)
let urlToAppend = docsURL.appendingPathComponent(fileNameToAppend)
guard let dataToAppend = try ? Data.contentsOf(url: urlToAppend) else { return }
guard let fileHandle = FileHandle(forWritingTo: fileURL) else { return }
fileHandle.seekToEndOfFile()
fileHandle.write(dataToAppend)
(跳过错误处理,关闭文件等)