Java Reference
In-Depth Information
Forexample, here we can build a path for a file:
String dir - name =" dataDir " ;
String file - name =" data.dat " ;
File file - data = new File (dir - name + File.separator
+ file - name);
Other talents of the File class include 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 case in which the
directory cannot be created is when the File object refers to an actual file that
already exists in the file system.
9.6 File I/O
The java.io package includes these base file stream classes:
FileInputStream - base class for binary file input
FileOutputStream - base class for binary file output
FileReader - read text files
FileWriter - write to text files
These classes treat a file as the source or destination. They each have several
overloaded constructors, including constructors that take a string file name as
the parameter and constructors that take an instance of File as a parameter. For
example, an input stream from a file can be created as follows:
File file - in = new File ( " data.dat " );
FileInputStream in = new FileInputStream (file - in);
If the file does not exist, the FileInputStream(File) constructor will throw
an instance of FileNotFoundException .
Usually, the FileInputStream object is wrapped with another stream to
obtain greater functionality. For example, BufferedInputStream is used to
smooth out the data flow as shown previously with the other “buffer” wrapper
classes.
Output streams to files are opened in a similar manner:
File file - out = new File ("tmp.dat");
FileOutputStream out = new FileOutputStream (file - out);
In this case, if the file doesn't exist, it will be created rather than throwing an
exception. As with input file streams, output streams are also usually wrapped with
one or more other streams to obtain greater functionality such as that provided
by BufferedOutputStream .
Search WWH ::




Custom Search