File Reading/Writing
Read a file:
- If no folder is specified in the file path, it will look for the file in the folder that this code file is in
- Every time the readLine function is called, it will read the next line
- A file should be closed after it is opened for reading/writing
Using try-with-resources (to ensure the file gets closed)
- You have to set up the reader/writer in the parenthesis after 'try'
- You don't have to close the file afterwards, it will be done automatically
- This is safer, because it ensures that the file gets closed, even if an error occurs
- You can have more resources within the parenthesis, separate them with semicolons
Read all lines of the file:
- The loop stops when it fails to read another line
Write to a file:
- This will create a new file if one of that name doesn't already exist
- If it already exists, it will overwrite it
Append to a file:
- This will add to the existing contents of a file
- The only code difference is the "true" added as an optional parameter when creating the FileWriter
Challenge
Write code that will write a file that stores a list of names, append a name to that file, then read the file and display its contents.