Append text or data to text file in Swift -
i have read read , write data text file
i need append data (a string) end of text file.
1 obvious way read file disk , append string end of , write back, not efficient, if dealing large files , doing in often.
so question "how append string end of text file, without reading file , writing whole thing back"?
so far have:
let dir:nsurl = nsfilemanager.defaultmanager().urlsfordirectory(nssearchpathdirectory.cachesdirectory, indomains: nssearchpathdomainmask.userdomainmask).last nsurl let fileurl = dir.urlbyappendingpathcomponent("log.txt") var err:nserror? // until find way append stuff files if let current_content_of_file = nsstring(contentsofurl: fileurl, encoding: nsutf8stringencoding, error: &err) { "\(current_content_of_file)\n\(nsdate()) -> \(object)".writetourl(fileurl, atomically: true, encoding: nsutf8stringencoding, error: &err) }else { "\(nsdate()) -> \(object)".writetourl(fileurl, atomically: true, encoding: nsutf8stringencoding, error: &err) } if err != nil{ println("cannot log: \(err)") }
you should use nsfilehandle, can seek end of file
let dir:nsurl = nsfilemanager.defaultmanager().urlsfordirectory(nssearchpathdirectory.cachesdirectory, indomains: nssearchpathdomainmask.userdomainmask).last nsurl let fileurl = dir.urlbyappendingpathcomponent("log.txt") let string = "\(nsdate())\n" let data = string.datausingencoding(nsutf8stringencoding, allowlossyconversion: false)! if nsfilemanager.defaultmanager().fileexistsatpath(fileurl.path!) { var err:nserror? if let filehandle = nsfilehandle(forwritingtourl: fileurl, error: &err) { filehandle.seektoendoffile() filehandle.writedata(data) filehandle.closefile() } else { println("can't open filehandle \(err)") } } else { var err:nserror? if !data.writetourl(fileurl, options: .datawritingatomic, error: &err) { println("can't write \(err)") } }
Comments
Post a Comment