Created
December 20, 2017 11:03
-
-
Save alemar11/cddca1e3810aca88950ede0c65635e92 to your computer and use it in GitHub Desktop.
FileHandleTextOutput
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| final public class FileHandleTextOutput: TextOutputStream { | |
| /// File path | |
| let path: String | |
| private let fileHandle: FileHandle | |
| public init?(path: String, append: Bool = false) { | |
| let expandedPath = (path as NSString).expandingTildeInPath | |
| guard let file = FileHandle(forWritingAtPath: expandedPath) else { return nil } | |
| fileHandle = file | |
| if append { | |
| fileHandle.seekToEndOfFile() | |
| } | |
| self.path = expandedPath | |
| } | |
| public func write(_ string: String) { | |
| fileHandle.write(string.data(using: .utf8)!) | |
| } | |
| deinit { | |
| fileHandle.closeFile() | |
| } | |
| } | |
| let testSream = FileHandleTextOutput(path: "/tmp/demo.txt", append: true) | |
| testSream?.write("Hello world.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment