In the previous chapter, we learned how to work with the streams. which provide a simple model for reading and writing data. However, streams don't support all the operations that are common with a disk file. In lesson, we will learn how to work with a file using the non-stream file I/O.
The File class deals with the
machine dependent files in a machine-independent manner i.e. it is easier to write
platform-independent code that examines and manipulates files using the File
class. This class is available in the java.lang
java.io.File is the central class that works
with files and directories. The instance of this class represents the
name of a file or directory on the host file system.
When a File object is created, the system doesn't check to the existence of a corresponding file/directory. If the file exist, a program can examine its attributes and perform various operations on the file, such as renaming it, deleting it, reading from or writing to it.
The constructors of the File class are shown in the table:
||Create File object for default directory (usually where program is located).|
||Create File object for directory path given as string.|
||Create File object for directory.|
Thus the statement can be written as:
File f = new File("<filename>");
The methods that are used with the file object to get the attribute of a corresponding file shown in the table.
||Returns true if file exists.|
||Returns true if this is a normal file.|
||true if "f" is a directory.|
||Returns name of the file or directory.|
||Returns true if file is hidden.|
||Returns time of last modification.|
||Returns number of bytes in file.|
||Deletes the file.|
||Renames f to File f2. Returns true if successful.|
||Creates a file and may throw IOException.|
Posted on: December 7, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles