Java Reference
In-Depth Information
Now for a simple example program to illustrate fi le output…
Example
Writes a single line of output to a text fi le.
import java.io.*;
public class FileTest1
{
public static void main(String[] args)
throws IOException
{
PrintWriter output =
new PrintWriter(new File("test1.txt"));
output.println("Single line of text!");
output.close();
}
}
Note that there is no 'append' method for a serial fi le in Java. After execution of
the above program, the fi le 'test1.txt' will contain only the specifi ed line of text. If the
fi le already existed, its initial contents will have been overwritten. This may or may
not have been your intention, so take care! If you need to add data to the contents of
an existing fi le, you still (as before Java SE 5) need to use a FileWriter object,
employing either of the following constructors with a second argument of true :
￿ FileWriter(String <fi leName>, boolean <append>)
￿ FileWriter(File <fi leName>, boolean <append>)
For example:
FileWriter addFile = new FileWriter("data.txt", true);
In order to send output to the fi le, a PrintWriter would then be wrapped around
the FileWriter :
PrintWriter output = new PrintWriter(addFile);
These two steps may, of course, be combined into one:
PrintWriter output =
new PrintWriter(
new FileWriter("data.txt", true);
It would be a relatively simple matter to write Java code to read the data back
from a text fi le to which it has been written, but a quick and easy way of checking
that the data has been written successfully is to use the relevant operating system
command. For example, on a PC, open up an MS-DOS command window and use
the MS-DOS type command, as below.
type test1.dat
Search WWH ::




Custom Search