Skip to main content

File and Directory handling

To work with files and directories package has a class File, which has all necessary methods and constructors to work with Files and Directories. The object of File class can be used to handle both file and directory.
You can create File object that will work as abstract representation of file or directory.  There are following constructors used to create File object.

1. public File(String pathname)
Creates a new File instance by converting the given pathname string into an abstract pathname. If the given string is the empty string, then the result is the empty abstract pathname.

e.g. File f=new File(“F:/java/programs”);
it creates  File object that is abstract represantioan of directory , F:\java\programs.
e.g. File f=new File(“F:/java/programs/”);
it creates  File object that is abstract represantioan of file

File f=new File(“F:/java/programs”);

2. File(File parent,String child)

E.g File f2=new File(f,”MyFile.txt”);
Creates a new File instance from a parent abstract pathname and a child pathname string.

Creating File object f2 from file object f and file MyFile.txt

3. public File(String parent,String child)
Creates a new File instance from a parent pathname string and a child pathname string.
E.g File f2=new File(“F:/java/programs”,”MyFile.txt”);
If parent is null then the new File instance is created as if by invoking the single-argument File constructor on the given child pathname string.
4. public File(URI uri)
Creates a new File instance by converting the given file: URI into an abstract pathname.
E.g File f2=new File(new URI(“”));
The exact form of a file: URI is system-dependent, hence the transformation performed by this constructor is also system-dependent.

File class Methods

new File(path);
Create File object for default directory (usually where program is located).
new File(dirpath, fname);
Create File object for directory path given as string.
new File(dir, fname);
Create File object for directory.
Default path separator (eg, "/" in Unix, "\" in Windows).
true if file exists.
true if this is a normal file.
true if f is a directory.
name of file or directory.
true if can read file.
true if can write file.
true if file is hidden.
Time of last modification.
Number of bytes in file.
Sets last modified time to long value t.
Make file read only. Returns true if successful.
path name.
path name (how is it different from above?).
path name. May throw IOException.
path with "file:" prefix and /'s. Directory paths end with /.
path with "file:" prefix and /'s. Directory paths end with /.
Deletes the file.
Create file, may throw IOException. true if OK; false if already exists.
Renames f to File f2. Returns true if successful.
Creates a directory. Returns true if successful.
Creates directory and all dirs in path. Returns true if successful.
Name of parent directory.
File of parent.
Array of file/directory names in dir.
Array of files/directories in dir.
As above after applying ff.

import java.util.*;

class FileTest {
    public static void main(String[] args) {
        try {
            File f = new File("F:/java/hemraj/Intro");
            long d;
            System.out.println("getName()          = " + f.getName());
            System.out.println("getAbsoluteFile().getName() = " 
                              + f.getAbsoluteFile().getName());
            boolean exists = f.exists();
            System.out.println("exists()           = " + exists);
            if (!exists) {
            System.out.println("canRead()          = " + f.canRead());
            System.out.println("canWrite()         = " + f.canWrite());
            System.out.println("getPath()          = " + f.getPath());
            System.out.println("getAbsolutePath()  = " + f.getAbsolutePath());
            System.out.println("getCanonicalPath() = " + f.getCanonicalPath());
            System.out.println("getAbsoluteFile()  = " + f.getAbsoluteFile());
            System.out.println("toURL()            = " + f.toURL());
            System.out.println("toURI()            = " + f.toURI());
            System.out.println("getParent()        = " + f.getParent());
            System.out.println("isAbsolute()       = " + f.isAbsolute());
            boolean isDirectory = f.isDirectory();
            System.out.println("isDirectory()      = " + isDirectory);
            System.out.println("isFile()           = " + f.isFile());
            System.out.println("isHidden()         = " + f.isHidden());
            System.out.println("lastModified()     = " + (d = f.lastModified())
                               + " = " + new Date(d));
            System.out.println("length()           = " + f.length());
            if (isDirectory) {
                String[] subfiles = f.list();
                for (int i=0; i<subfiles.length; i++) {
                    System.out.println("file in this dir   = " + subfiles[i]);
        } catch (IOException iox) {

getName()          = Intro
getAbsoluteFile().getName() = Intro
exists()           = true
canRead()          = true
canWrite()         = true
getPath()          = F:\java\hemraj\Intro
getAbsolutePath()  = F:\java\hemraj\Intro
getCanonicalPath() = F:\java\Hemraj\Intro
getAbsoluteFile()  = F:\java\hemraj\Intro
toURL()            = file:/F:/java/hemraj/Intro/
toURI()            = file:/F:/java/hemraj/Intro/
getParent()        = F:\java\hemraj
isAbsolute()       = true
isDirectory()      = true
isFile()           = false
isHidden()         = false
lastModified()     = 1173723889984 = Mon Mar 12 10:24:49 PST 2007
length()           = 0
file in this dir   = A.class
file in this dir   =
file in this dir   = Args.class
file in this dir   =
file in this dir   = Main.class
file in this dir   =
file in this dir   =
file in this dir   = WhileDemo.class
file in this dir   =
Press any key to continue...

File Path Separator:-

The system-dependent default name-separator character. On UNIX systems the value of this field is '/'; on Microsoft Windows systems it is '\\'.
The system-dependent default name-separator character, represented as a string for convenience.
The system-dependent path-separator character. This character is used to separate filenames in a sequence of files given as a path list. On UNIX systems, this character is ':'; on Microsoft Windows systems it is ';'.
The system-dependent path-separator character, represented as a string for convenience.

class FileHandle {
    public static void main(String[] args) {
            char sc=File.separatorChar;
            String s=File.separator;
            char psc=File.pathSeparatorChar;
            String ps=File.pathSeparator;
            File f1 = new File("F:"+s+"java"+s+"hemraj"+s+"Intro","");
            File f2 = new File("F:"+sc+"java"+sc+"hemraj"+sc+"Intro","");
            File f3 = new File("F:"+s+"java"+s+"hemraj"+s+"Intro"+psc+"F:"+s+"java");
            File f4 = new File("F:"+s+"java"+s+"hemraj"+s+"Intro"+ps+"F:"+s+"java");
            System.out.println("Paht f1= "+ f1.getPath());
            System.out.println("Paht f2= "+ f2.getPath());
            System.out.println("Paht f3= "+ f3.getPath());
            System.out.println("Paht f4= "+ f4.getPath());
Paht f1= F:\java\hemraj\Intro\
Paht f2= F:\java\hemraj\Intro\
Paht f3= F:\java\hemraj\Intro;F:\java
Paht f4= F:\java\hemraj\Intro;F:\java

Filename Filter

If you want to access only some files which match specified extension for example “.java”,”.txt” or anything then you need to check whether particular extension match or not. If it matches then access it otherwise leaves it.

Here package provides an interface FilenameFilter which can be used to user defined filter. It has only one method having return type boolean.
Now if you want that you have a class and you want that if should work as filter then follow two steps to build your own filter
->  implements FilenameFilter into that class which is going to be filter
            e.g. class MyFilter implements FilenameFilter
->  define method having prototype public boolean accept(File dir, String name)
     e.g. public boolean accept(File dir,String name)

Now this class will work as filter. Here accept() method is used by list() method to perform filtering. And it will return Boolean value as you define in your program.

Here MyFilter class is filter because it has all properties which are necessary to become a filter because you have implemented FilenameFilter interface.
accept() method returns false/true according to return statement and name.endsWith(“.java)method returns false if name String ends with .java otherwise return false.


class MyFilter implements FilenameFilter
    public boolean accept(File dir,String name)
        return name.endsWith(".java");

Using filter

To use filter in program you have to do follwing steps
Create an object of filter class (e.g.  MyClass). Assign reference to FilenameFilter type valiable.
pass this object into list() method as an argument
Now list method returns names of files those matches specified name (which has been passed into endsWith() method in accept() method of Filter class) at the end of name of file.

class FilterTest
    public static void main(String args[])
        File f=new File("F:"+File.separator+"java"+File.separator+"hemraj"+File.separator+"io");
        System.out.println("List of files without filter");
        String str1[]=f.list();
        for(int i=0;i<str1.length;i++)
        //Displaying file’s list using filter
        System.out.println("List of files with filter");
        FilenameFilter ft=new MyFilter(); 
        String str2[]=f.list(ft);
        for(int i=0;i<str2.length;i++)
List of files without filter
List of files with filter


Popular posts from this blog

Using HyperSQL (HSQLDB)

HSQLDB is a portable RDBMS implemented in pure java. It can be embedded with your application as well as can be used separately. It is very a small database that supports almost all features of the standard database system. It comes with small jar file that can be found in lib folder. The HSQLDB jar package is located in the /lib directory of the ZIP package and contains several components and programs. Core components of jar file are : HyperSQL RDBMS Engine (HSQLDB), HyperSQL JDBC Driver, Database Manager, and Sql Tool. Installing and Using Download: download latest release of HyperSQL database from website and extract it. You will see following contents. Here "bin" directory contains some batch files those can be used to run a swing based GUI tool. You can use runManagerSwing.bat to connect to database, but database must be on before running it. Directory lib contains File hsqldb.jar . It is the database to be used by you. Running database First

How to handle values from dynamically generated elements in web page using struts2

Some time you will see the form containing the button " Add More " . This facility is provided for the user to get the values for unknown number of repeating for some information. for example when you are asking to get the projects details from user, you need to put the option to add the more project for the user since you don't known how many projects user have. In the HTML form, you repeat the particular section to get the multiple values for those elements. In Html page , you can put the option to add new row of elements or text fields by writing the java script or using JQuery API. Now, the question is that how to capture the values of dynamically generated text fields on the server. Using the servlet programming you can get the values by using getParameters() method that resultants the array of the parameter having the same name. But this limit you to naming the text fields in the HTML form. To ally this approach, you have to take the same name for t

In Process Mode of HSQLDB in web application.

If you want to use the database into your web application, you can use the HSQLDB in In_Process mode. In this mode, you can embed the HSQLDB into your web application and it runs as a part of your web application programm in the same JVM. In this mode, the database does not open any port to connect to the application on the hosing machine and you don't need to configure anything to access it. Database is not expposed to other application and can not be accessed from any dabase tools like dbVisualizer etc. In this mode ,database will be unknown from any other person except you. But in the 1.8.0 version, you can use Server intance for external as well as in process access.  To close the databse, you can issue SHUTDOWN command as an SQL query.   In the in-process mode, database starts from JDBC with the associated databse file provided through  connection URL. for example   DriverManager.getConnection("jdbc:hsqldb:mydatabase","SA","");   Here myd