
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Read and Write a String from a Text File
In Swift, you can read and write a string from a text file using the String(contentsOfFile:) and write(toFile:atomically:encoding:) methods of the String class. You will see some examples of file reading and writing in Swift.
String(contentsOfFile:)
A class method for creating a string from a file's content is provided by the String class. This method is an initializer where the path to the file must be given. For instance, you can read the contents of local files by passing the path to the main bundle. A new string containing the file's content is returned by this procedure.
Keep in mind that this method may return nil if the content or path is invalid or for any other reason. The try-catch block can be used to manage this situation.
write(toFile:atomically:encoding:)
In this method, an instance of the String class writes the contents of the string to a file. The method takes three parameters ?
toFile ? The path of the file to write the string to.
atomically ? A Boolean value that determines whether the file should be written atomically. The file is written to a temporary location and then renamed to the final location if set to true. This can help prevent data loss in case of a failure during the write operation.
encoding ? The encoding to use when writing the string to the file. The default value is .utf8.
Following is an example of how to read a string from a text file
Please note here before jumping to read the file. Here, we added a file with the name "example.txt" to the Xcode project. We will read the same file. In that text file, we added the string content which is the following ?
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
Example
The same string content will be read from the example.txt file ?
func readString() { do { // creating a path from the main bundle if let bundlePath = Bundle.main.path(forResource: "example.txt", ofType: nil) { let stringContent = try String(contentsOfFile: bundlePath) print("Content string starts from here-----") print(stringContent) print("End at here-----") } } catch { print(error) } }
Output
Content string starts from here----- Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. End at here-----
And here is an example of how to write a string to a text file
To write the string content to a file, we will use the same file used in the above example.
Example
func writeString() { do { // creating path from main bundle if let bundlePath = Bundle.main.path(forResource: "example.txt", ofType: nil) { let stringToWrite = "This is a string to write to a file." try? stringToWrite.write(toFile: bundlePath, atomically: true, encoding: .utf8) let stringContent = try String(contentsOfFile: bundlePath) print("Content string starts from here-----") print(stringContent) print("End at here-----") } } catch { print(error) } }
Output
Content string starts from here----- This is a string to write to a file. End at here-----
Note that the bundlePath variable is the path to the file in the bundle. You could also use a custom path if the file is not in the bundle.
Keep in mind that the contentsOfFile: and write(toFile:atomically:encoding:) methods can throw errors, so it is recommended to use the try? or try! keywords or the do-catch statement to handle them.
Conclusion
The above-mentioned methods are used for reading the contents of a file into a string and then writing a string to a file.
You should note that when you work with files, it is required to handle errors. It is because there are more chances to come errors while reading or writing the files. You can provide a path that might be custom or a path in the bundle. Also, you can provide the path of a file system using FileManager.