Java FileReader and FileWriter Streams

FileReader and FileWriter are character streams, belonging to the Reader and Writer hierarchies, that are specialized for performing file input and output. These streams handle 16-bit Unicode characters, and so would normally be used when handling files containing textual data. Java also provides equivalent byte streams, FileInputStream and FileOutputStream, that handle ISO-Latin-1 8-bit bytes. Typically, these streams would be used for handling image and sound data.

Java provides a class, java.io.File, for representing files. The constructor File(filename) creates a file instance. filename is a string containing just the file name or the full directory path name; for example, File1.txt or \\MyJavaFiles\\File1.txt on Windows. In the former case, the physical file will reside in the same directory as the Java program accessing the file. Note the use of double backslash characters in the Windows path name, since a single backslash is the escape character within a string. You can use a single forward slash, for example, /MyJavaFiles/File1.txt, for both Windows and Unix directory paths. To ensure portability beyond Windows or Unix environments, the java.io.File class provides a separator static variable that provides the file separator for the local host.

A number of methods in the File class provide information about the properties or existence of files. For example, the method File.exists() returns the boolean true if
the specified file physically exists.

To open a file for reading, we create a FileReader object on the file. Either a string or file object should be supplied to the FileReader constructor. There are a number of methods in the java.io.FileReader class, the most useful being read. This method is overloaded to take a string, a single character, or an array of characters as arguments.

To open a file for writing, we create a FileWriter object on the file. Again, either a string or file object should be supplied to the FileWriter constructor. There are a number of methods in the java.io.FileWriter class, the most useful being write. This method is overloaded to take a string, a single character, or an array of characters as arguments.

No comments:

Post a Comment