14 10 Creation and reading of a file
In the previous lesson we played with creation and reading separately. Here we combine both into a single example using FileWriter and FileReader. We keep only the variable that holds the file we want to work with and remove the rest of the leftover code.
In Java, the classes that read a file inherit from InputStream (or, for character streams, Reader). The interesting thing is that each reader class exposes several constructors. FileReader can be built from a File object or from a String path, so we will use both in the example to see how that works.
Write, flush, read, print
- Instantiate a
FileWriterwith the file as a constructor argument. - Call
write(...)to push characters into the buffer. - Call
flush()to actually send the buffered content to disk without permanently closing the stream. - Open a
FileReaderon the same file, prepare achar[]array as the read buffer, then loop and callread(buffer)until the end of the file. - Print every character with
System.out.print(...)so the content reappears in the console.
As always with file streams, do not forget to close both the writer and the reader once you are done. Closing them releases the underlying file handle and lets the operating system reclaim the resources. With this small program we have a full round trip: data goes from memory into the file, then comes back from the file into memory.