A brief overview of flow manipulation (including byte streams, character streams, files) in Java.
There are four essential kinds of objects that represent flows of information in Java.
-
InputStream: to read flows of bytes.
-
OutputStream: to write flows of bytes.
-
Reader: to read flows of characters.
-
Writer: to write flows of characters.
It is typical for a flow of character to be encoded in a flow of bytes, for example, a text file stored on your hard disk contain character data but also byte data. Character flows should be used preferably to byte flows in that case, as they represent higher level information.
Readers are generally obtained from a byte source (and writers, from a byte sink). In that case they must be accompanied by a character encoding, which specifies how bytes and characters relate. (Java permits to omit this information in some cases, but not doing so makes your program fragile as some default will be used implicitly.)
Two essential classes help you deal with files: Path and Files. For example, use Files#newBufferedWriter() to obtain a Writer that writes to a file.
Always close your streams after use. Use the try-with-resources statement for this.
See Oracle’s Basic I/O tutorial.