Certification
SCJP
Files and directories are accessed and manipulated via the java.io.File class. The File class does not actually provide for input and output to files. It simply provides an identifier of files and directories.
Always remember that just because a File object is created, it does not mean there actually exists on the disk a file with the identifier held by that File object.
The File class includes several overloaded constructors. For example, the following instance of File refers to a file named myfile.txt in the current directory of the program that the JVM is running:
File file = new File ("myfile.txt");
Again, the file myfile.txt may or may not exist in the file system. An attempt to use File object that refers to a file that does not exist will cause a FileNotFoundException to be thrown.
The File instance can also created with a filename that includes path:
File fileA = new File("/tmp/filea.txt");
Another overloaded constructor allows separate specification of the path and the file name:
File fileA = new File("/tmp", "filea.txt");
Directories can also be specified:
File directoryA = new File("/tmp");
There are a number of useful methods in File, e.g.:
..... boolean exist(); // does the file exist ..... |
There are also methods to get the file name and path components, to make a directory, to get a listing of the files in a directory, etc.
..... String getName(); // get the name of the file (no path included) ..... |
NOTE, the getCanonicalPath() method first converts this pathname to absolute form if necessary, as if by invoking the getAbsolutePath() method, and then maps it to its unique form in a system-dependent way. This typically involves removing redundant names such as "." and ".." from the pathname, resolving symbolic links (on UNIX platforms), and converting drive letters to a standard case (on Microsoft Windows platforms).
NOTE, that path names use different separator characters on different hosts. Windows uses "\", Unix - "/", Macintosh - ":". The static variables:
..... File.separator // string with file separator ..... |
can be used to insure that your programs are platform independent. For example, this snippet shows how to build a platform independent path:
..... String dirName = "dataDir"; ..... |
The File class includes the method:
boolean mkdir();
This method will create a directory with the abstract path name represented by the File object if that File object represents a directory. The method returns true if the directory creation succeeds and false if not. A situation in which the directory cannot be created is, for example, when the File object refers to an actual file that already exists in the file system.
Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change.
This example lists the files and subdirectories in a directory:
..... File dir = new File("directoryName"); ..... |
It is also possible to filter the list of returned files. This example does not return any files that start with '.' :
..... FilenameFilter filter = new FilenameFilter() { ..... |
The list of files can also be retrieved as File objects:
File[] files = dir.listFiles();
This filter only returns directories:
..... FileFilter fileFilter = new FileFilter() { ..... |
Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.
FileReader is meant for reading streams of characters. For reading streams of raw bytes, consider using a FileInputStream.
..... public FileReader(String fileName) throws FileNotFoundException ..... |
Some methods:
..... // Read a single character ..... |
..... try { ..... |
Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.
In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example:
BufferedReader in = new BufferedReader(new FileReader("foo.in"));
will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.
Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.
Constructors:
..... public BufferedReader(Reader in, int sz) ..... |
Some methods:
..... // Read a single character ..... |
..... // Example reads from from one file and writes to another. ..... |
Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.
Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileWriter (or other file-writing object) at a time. In such situations the constructors in this class will fail if the file involved is already open.
FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream.
Constructors:
.....
public FileWriter(String fileName) throws IOException
// if 'append' parameter is 'true', then data will be written
// to the end of the file rather than the beginning
public FileWriter(String fileName, boolean append) throws IOException
public FileWriter(File file) throws IOException
public FileWriter(File file, boolean append) throws IOException
public FileWriter(FileDescriptor fd)
.....
Some methods:
..... // Write an array of characters ..... |
Writing to a File. If the file does not already exist, it is automatically created:
..... try { ..... |
Appending to a File:
..... try { ..... |
Write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.
The buffer size may be specified, or the default size may be accepted. The default is large enough for most purposes.
A newLine() method is provided, which uses the platform's own notion of line separator as defined by the system property line.separator. Not all platforms use the newline character ('\n') to terminate lines. Calling this method to terminate each output line is therefore preferred to writing a newline character directly.
In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters. For example:
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
will buffer the PrintWriter's output to the file. Without buffering, each invocation of a print() method would cause characters to be converted into bytes that would then be written immediately to the file, which can be very inefficient.
Constructors:
..... public BufferedWriter(Writer out) ..... |
Some methods:
..... // Write a portion of an array of characters ..... |
..... try { ..... |
Print formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output. These methods use the platform's own notion of line separator rather than the newline character.
Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError().
..... import java.io.BufferedWriter; ..... |
The test.txt file contents:
30102.9true
______________
Author: Mikalai Zaikin. Please Click Here to visit Authors site for any updates and changes to the study notes.