Writing and Reading a Note
Now that you can create files, it's time to add real content. You'll write a short note to a text file and then read it back to confirm it was saved correctly. This is a core feature of any note-taking application.
This exercise is part of the course
Input/Output and Streams in Java
Exercise instructions
- Write the text
"Start from the beginning"
to a file named"note.txt"
. - Create a
FileWriter
inappend
mode for"note.txt"
asfwAppendMode
. - Add the text
" Add to the end"
to the file without overwriting its content. - Use
FileReader
to read the content of the file and display it on the console, one character at a time.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
class FileReadWrite {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("note.txt");
// Write "Start from the beginning" to the file
fw.____("Start from the beginning");
fw.close();
// Create a FileWriter in append mode
FileWriter fwAppendMode = new ____("note.txt", ____);
// Add " Add to the end" to the end of file
fwAppendMode.____(" Add to the end");
fwAppendMode.close();
FileReader fr = new FileReader("note.txt");
int character;
// Read the file content character by character
while ((character = fr.____()) != -1) {
System.out.print((char) character);
}
fr.close();
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}