swiftfilehandler

Merge/Append two files


I have two files, File1 & File2. I want to append File2 at the end of File1.

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

I was using this function to add string at the end of file. I didn't find anything to append file at the end. Can any one help me here if I am missing anything.


Solution

  • As rmaddy says, you are using the wrong code to get the documents directory. For that you should use code something like this:

    guard let docsURL =  try? FileManager.default.url(for: .documentDirectory, 
                     in: .userDomainMask, 
                     appropriateFor: nil, 
                     create: true else { return }
    

    Then you need code to read the file that you want to append and use write to append it:

    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)
    

    (Skipping error handling, closing the file, etc.)