In order to correctly read and write text files, you need to understand that those read/write operations always use
an implicit character encoding to translate raw bytes - the 1s and 0s - into text.
When a text file is saved, the tool that saves it must always use a character encoding
(UTF-8 is recommended).
There's a problem, however.
The character encoding is not, in general, explicit: it's not saved as part of the file itself.
Thus, a program that consumes a text file should know beforehand what its encoding is.
If it doesn't, then the best it can do is make an assumption.
Problems with encoding usually show up as weird characters in a tool that has read the file.

The FileReader
and FileWriter
classes are a bit tricky, since they implicitly use the system's default character encoding. If this
default is not appropriate, the recommended alternatives are, for example:

This example demonstrates using
Scanner to read a file containing lines of structured data.
One Scanner is used to read in each line, and a second Scanner is used
to parse each line into a simple name-value pair.
The Scanner class is only used for reading, not for writing.

Name is : 'height', and Value is : '167cm'
Name is : 'mass', and Value is : '65kg'
Name is : 'disposition', and Value is : '"grumpy"'
Name is : 'this is the name', and Value is : 'this is the value'
Done.

Example 3 - JDK < 7

The try-with-resources feature is not available prior to JDK 7.
In this case, you need to exercise care with respect to the close method:

it always needs to be called, or else resources will leak

it will automatically flush the stream, if necessary

calling close on a "wrapper" stream will automatically call close
on its underlying stream

closing a stream a second time has no consequence

when called on a Scanner, the
close operation only works if the item passed to its constructor implements Closeable.
Warning: if you pass a File to a Scanner, you will not be able to close it!
Try using a FileReader instead.

Here's a fairly compact example (for JDK 1.5) of reading and writing a text file, using an explicit encoding.
If you remove all references to encoding from this class, it will still work -- the system's default
encoding will simply be used instead.

This example uses FileReader and FileWriter, which implicitly use the system's default encoding.
It also uses buffering.
To make this example compatible with JDK 1.4, just change StringBuilder to StringBuffer: