Append Text or Data to Text File in Swift

Swift. How to append text line to top of file.txt?

This should be okay:
First, get the old data and after that append the new one and write everything.

let msgWithLine = text + "\n"
do {
let fileHandle = try FileHandle(forWritingTo: file)
fileHandle.seek(toFileOffset: 0)
let oldData = try String(contentsOf: file, encoding: .utf8).data(using: .utf8)!
var data = msgWithLine.data(using: .utf8)!
data.append(oldData)
fileHandle.write(data)
fileHandle.closeFile()
} catch {
print("Error writing to file \(error)")
}

I didn't test the code it may have some problems.

Another possible solution is to write at the end of the file and to invert the file when you read it.

Append some text at the end of text file in swift

Your code looks like Swift 1 to me and even then, it's not valid Swift 1 either. If you are using Swift 2 or later, try this:

let dir = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.CachesDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last!
let fileurl = dir.URLByAppendingPathComponent("log.txt")

let string = "\(NSDate())\n"
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!

if NSFileManager.defaultManager().fileExistsAtPath(fileurl.path!) {
do {
let fileHandle = try NSFileHandle(forWritingToURL: fileurl)

fileHandle.seekToEndOfFile()
fileHandle.writeData(data)
fileHandle.closeFile()
} catch {
print("Can't open fileHandle \(error)")
}
} else {
do {
try data.writeToURL(fileurl, options: .DataWritingAtomic)
} catch {
print("Can't write \(error)")
}
}

Append data to txt file in Swift 3

You can use a FileHandle for appending the existing file after checking if the file already exists.

let titleString = "Line, Item 1, Item 2, Item 3"
var dataString: String
let list1 = [1, 2, 3, 4, 5]
let list2 = ["a", "b", "c", "d", "e"]
let list3 = ["p", "q", "r", "s", "t"]

do {
try "\(titleString)\n".write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
} catch {
print(error)
}

for i in 0...4 {
dataString = String(list1[i]) + ": " + list2[i] + list3[i] + "\n"
//Check if file exists
do {
let fileHandle = try FileHandle(forWritingTo: fileURL)
fileHandle.seekToEndOfFile()
fileHandle.write(dataString.data(using: .utf8)!)
fileHandle.closeFile()
} catch {
print("Error writing to file \(error)")
}
print(dataString)
print("Saving data in: \(fileURL.path)")
}

Output:

Line, Item 1, Item 2, Item 3
1: ap
2: bq
3: cr
4: ds
5: et

Append text to document file in Swift

I found your problem here: Append text or data to text file in Swift

  • Will append to the text file if the file exists.
  • Will create a new file if the text file doesn't exist.

    class Logger {

    static var logFile: URL? {
    guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil }

    let formatter = DateFormatter()
    formatter.dateFormat = "dd-MM-yyyy"
    let dateString = formatter.string(from: Date())
    let fileName = "\(dateString).log"

    return documentsDirectory.appendingPathComponent(fileName)
    }

    static func log(_ message: String, functionName: String = #function, filename: String = #file, line: Int = #line) {
    guard let logFile = logFile else {
    return
    }

    let className = filename.components(separatedBy: "/").last

    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS "
    let timestamp = formatter.string(from: Date())
    guard let data = ("[\(timestamp)] [\(className ?? "")] \(functionName)\(line): \(message)" + "\n").data(using: String.Encoding.utf8) else { return }

    if FileManager.default.fileExists(atPath: logFile.path) {
    if let fileHandle = try? FileHandle(forWritingTo: logFile) {
    fileHandle.seekToEndOfFile()
    fileHandle.write(data)
    fileHandle.closeFile()
    }
    } else {
    try? data.write(to: logFile, options: .atomicWrite)
    }
    }
    }

Append new string to txt file in swift 2

I think you must use NSFileHandle:

  let dir:NSURL = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.CachesDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last as NSURL
let fileurl = dir.URLByAppendingPathComponent("file.txt")

let string = "\(NSDate())\n"
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!

if NSFileManager.defaultManager().fileExistsAtPath(fileurl.path!) {
var error:NSError?
if let fileHandle = NSFileHandle(forWritingToURL: fileurl, error: &error) {
fileHandle.seekToEndOfFile()
fileHandle.writeData(data)
fileHandle.closeFile()
}
else {
println("Can't open fileHandle \(error)")
}
}
else {
var error:NSError?
if !data.writeToURL(fileurl, options: .DataWritingAtomic, error: &error) {
println("Can't write \(error)")
}
}

Append CSV or Text File in Swift 2

Create a file name:

let fileName = "file"

Find the URL of the document directory:

let DocumentDirURL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)

Append the file name and extension to create the absolute file path:

let fileURL = DocumentDirURL.URLByAppendingPathComponent(fileName).URLByAppendingPathExtension("csv")

Use NSFileHandle to open the file:

let file: NSFileHandle? = NSFileHandle(forUpdatingAtPath: fileURL.path!)

Write data at the end of the file:

if file == nil {
NSLog("File open failed")
} else {
// assuming data contains contents to be written
let fileData = data.dataUsingEncoding(NSUTF8StringEncoding)
// seek to end of the file to append at the end of the file.
file?.seekToEndOfFile()
file?.writeData(fileData!)
file?.closeFile()
}

How to open file and append a string in it, swift

If you want to be able to control whether to append or not, consider using OutputStream. For example:

do {
let fileURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
.appendingPathComponent("votes.txt")

guard let outputStream = OutputStream(url: fileURL, append: true) else {
print("Unable to open file")
return
}

outputStream.open()
let text = "some text\n"
try outputStream.write(text)
outputStream.close()
} catch {
print(error)
}

By the way, this is an extension that lets you easily write a String (or Data) to an OutputStream:

extension OutputStream {
enum OutputStreamError: Error {
case stringConversionFailure
case bufferFailure
case writeFailure
}

/// Write `String` to `OutputStream`
///
/// - parameter string: The `String` to write.
/// - parameter encoding: The `String.Encoding` to use when writing the string. This will default to `.utf8`.
/// - parameter allowLossyConversion: Whether to permit lossy conversion when writing the string. Defaults to `false`.

func write(_ string: String, encoding: String.Encoding = .utf8, allowLossyConversion: Bool = false) throws {
guard let data = string.data(using: encoding, allowLossyConversion: allowLossyConversion) else {
throw OutputStreamError.stringConversionFailure
}
try write(data)
}

/// Write `Data` to `OutputStream`
///
/// - parameter data: The `Data` to write.

func write(_ data: Data) throws {
try data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) throws in
guard var pointer = buffer.baseAddress?.assumingMemoryBound(to: UInt8.self) else {
throw OutputStreamError.bufferFailure
}

var bytesRemaining = buffer.count

while bytesRemaining > 0 {
let bytesWritten = write(pointer, maxLength: bytesRemaining)
if bytesWritten < 0 {
throw OutputStreamError.writeFailure
}

bytesRemaining -= bytesWritten
pointer += bytesWritten
}
}
}
}

For Swift 2 rendition, see previous revision of this answer.



Related Topics



Leave a reply



Submit