Working With File

In the previous chapter, we learned how to work with the streams.

Working With File


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 package.
The 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:

 Constructor  Description
 File(path)  Create File object for default directory (usually where program is located).
 File(dirpath,fname)  Create File object for directory path given as string.
 File(dir, fname)  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.

 Method  Description
 f.exists()  Returns true if file exists.
 f.isFile()  Returns true if this is a normal file.
 f.isDirectory()  true if "f" is a directory.
 f.getName()  Returns name of the file or directory.
 f.isHidden()  Returns true if file is hidden.
 f.lastModified()  Returns time of last modification.
 f.length()  Returns number of bytes in file.
 f.getPath()  path name.
 f.delete()  Deletes the file.
 f.renameTo(f2)  Renames f to File f2. Returns true if successful.
 f.createNewFile()  Creates a file and may throw IOException. 
Share on Google+Share on Google+

Working With File

Posted on: December 7, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Working With File   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image