Working with Files in Swift Using FileHandle
Learn how to read and write to files from within Swift using the FileHandle class.
The FileHandle
class provides a range of methods designed to provide a more advanced mechanism for working with files. In addition to files, this class can also be used for working with devices and network sockets. In the following sections, we will look at some of the more common uses for this class.
Creating a FileHandle object
A FileHandle
object can be created when opening a file for reading, writing or updating (in other words both reading and writing). Having opened a file, it must subsequently be closed when we have finished working with it using the closeFile
method. For example, if an attempt to open a file fails because an attempt is made to open a non-existent file for reading, these methods return nil
.
For example, the following code excerpt opens a file for reading (hence the forReadingAtPath
declaration), and then closes it without actually doing anything to the file:
import Foundationlet filePath1 = "/usercode/myfile1.txt"let file: FileHandle? = FileHandle(forReadingAtPath: filePath1)if file == nil {print("File open failed")} else {print("File open successful. Closing file...")file?.closeFile()}
If we had wanted to write to the file ...