|
|
Reading and Writing |
File streams are perhaps the easiest streams to understand. Simply put, the file streams--FileReader,
FileWriter,
FileInputStream, and
FileOutputStream--each read or write from a file on the native file system. You can create a file stream from a filename, a
Fileobject, or a
FileDescriptorobject.
The following
Copyprogram usesFileReaderandFileWriterto copy the contents of a file namedfarrago.txtinto a file calledoutagain.txt:This program is very simple. It opens aimport java.io.*; public class Copy { public static void main(String[] args) throws IOException { File inputFile = new File("farrago.txt"); File outputFile = new File("outagain.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } }FileReaderonfarrago.txtand opens aFileWriteronoutagain.txt. The program reads characters from the reader as long as there's more input in the input file. When the input runs out, the program closes both the reader and the writer.Notice the code that the
Copyprogram uses to create aFileReader:This code creates aFile inputFile = new File("farrago.txt"); FileReader in = new FileReader(inputFile);Fileobject that represents the named file on the native file system.Fileis a utility class provided byjava.io. This program uses this object only to construct aFileReaderonfarrago.txt. However, it could useinputFileto get information aboutfarrago.txt, such as its full pathname.After you've run the program, you should find an exact copy of
farrago.txtin a file namedoutagain.txtin the same directory. Here is the content of the file:
Remember thatSo she went into the garden to cut a cabbage-leaf, to make an apple-pie; and at the same time a great she-bear, coming up the street, pops its head into the shop. 'What! no soap?' So he died, and she very imprudently married the barber; and there were present the Picninnies, and the Joblillies, and the Garyalies, and the grand Panjandrum himself, with the little round button at top, and they all fell to playing the game of catch as catch can, till the gun powder ran out at the heels of their boots. Samuel Foote 1720-1777FileReaderandFileWriterread and write 16-bit characters. However, most native file systems are based on 8-bit bytes. These streams encode the characters as they operate according to the default character-encoding scheme. You can find out the default character-encoding by usingSystem.getProperty("file.encoding"). To specify an encoding other than the default, you should construct anOutputStreamWriteron aFileOutputStreamand specify it. For information about encoding characters, see the Writing Global Programs trail.For the curious, here is another version of this program, CopyBytes, which uses
FileInputStreamandFileOutputStreamin place ofFileReaderandFileWriter.
|
|
Reading and Writing |