Java Reference
In-Depth Information
The following snippet shows how to append data to an existing file:
File file
-
out
=
new File (
"
old.dat
"
);
FileOutputStream out
=
new FileOutputStream (file
-
out, true);
The second parameter in the constructor indicates that the file should be opened
for appending.
RandomAccessFile
can also be used for appending. It is dis-
cussed in the Web Course Chapter 9:
Supplements
section.
9.6.1 Text output to a file
We can use the
FileWriter
stream class to write character data to a file. The
following
PrintWriterFileApp
example gets the name for an output file
either from a parameter on the command line or from a default. The program
follows closely to
PrintWriterApp
in Section 9.4.1 except that instead of
starting with the
PrintStream
object referenced by
System.out
,wecreate
a
FileWriter
for a
File
object and then wrap this with a
BufferedWriter
and a
PrintWriter
. These two wrappers give us the efficiency of stream buffer-
ing and a handy set of print methods.
import java.io.*;
/**
*Demonstrate wrapping streams to send text and primitive
*type values to a file.
**/
public class
PrintWriterFileApp
{
public static void main (String[] args)
{
File file = null;
// Get the file from the argument line.
if (args.length
>
0) file
=
new File (args[0]);
if (file
==
null)
{
System.out.println (
"
Default: textOutput.txt
"
);
file
=
new File (
"
textOutput.txt
"
);
}
// Create a FileWriter stream to a file and then wrap
// a PrintWriter object around the FileWriter to print
// primitive values as text to the file.
try
{
// Create a FileWriter stream to the file
FileWriter file
-
writer
=
new FileWriter (file);
Search WWH ::
Custom Search