File Reading/Writing
Read a file
try {
BufferedReader myReader = new BufferedReader( new FileReader("myFolder\\myFile.txt") );
String line1 = myReader.readLine();
String line2 = myReader.readLine();
myReader.close();
}
catch (IOException e) {
// Handle this
}
- 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)
try ( BufferedReader myReader = new BufferedReader( new FileReader("myFolder\\myFile.txt") ) )
{
String line1 = myReader.readLine();
}
catch (IOException e) {
// Handle this
}
- 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
try (BufferedReader myReader = new BufferedReader( new FileReader("myFolder\\myFile.txt") ) )
{
String line;
while ( (line = myReader.readLine()) != null ) {
System.out.println( line );
}
}
catch (IOException e) {
// Handle this
}
- The loop stops when it fails to read another line.
Write to a file
try (BufferedWriter myWriter = new BufferedWriter(new FileWriter("myFolder\\myFile.txt")) )
{
myWriter.write("testing 123\n");
}
catch (IOException e) {
// Handle this
}
- 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
try (BufferedWriter myWriter = new BufferedWriter(new FileWriter("myFolder\\myFile.txt", true)) )
{
myWriter.write("testing 456\n");
}
catch (IOException e) {
// Handle this
}
- 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.
Quiz
Completed