File and Directory handling

To work with files and directories java.io 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/MyClass.java”);
it creates  File object that is abstract represantioan of file MyClass.java




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(“http://www.yahoo.com”));
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.
File.separator;
Default path separator (eg, "/" in Unix, "\" in Windows).
f.exists();
true if file exists.
f.isFile();
true if this is a normal file.
f.isDirectory();
true if f is a directory.
f.getName();
name of file or directory.
f.canRead();
true if can read file.
f.canWrite();
true if can write file.
f.isHidden();
true if file is hidden.
f.lastModified();
Time of last modification.
f.length();
Number of bytes in file.
f.setLastModified(t);
Sets last modified time to long value t.
f.setReadOnly();
Make file read only. Returns true if successful.
f.getPath();
path name.
f.getAbsolutePath();
path name (how is it different from above?).
f.getCanonicalPath();
path name. May throw IOException.
f.toURL();
path with "file:" prefix and /'s. Directory paths end with /.
f.toURI();
path with "file:" prefix and /'s. Directory paths end with /.
f.delete();
Deletes the file.
f.createNewFile();
Create file, may throw IOException. true if OK; false if already exists.
f.renameTo(f2);
Renames f to File f2. Returns true if successful.
f.mkdir();
Creates a directory. Returns true if successful.
f.mkdirs();
Creates directory and all dirs in path. Returns true if successful.
f.getParent();
Name of parent directory.
f.getParentFile();
File of parent.
dir.list();
Array of file/directory names in dir.
dir.listFiles();
Array of files/directories in dir.
dir.listFiles(ff);
As above after applying java.io.FileFilter ff.

import java.io.*;
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.exit(1);
            }
            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) {
           System.err.println(iox);
        }
    }
}

output:
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   = A.java
file in this dir   = Args.class
file in this dir   = Args.java
file in this dir   = Main.class
file in this dir   = MyClass.java
file in this dir   = UserInput.java
file in this dir   = WhileDemo.class
file in this dir   = WhileDemo.java
Press any key to continue...

File Path Separator:-

separatorChar
The system-dependent default name-separator character. On UNIX systems the value of this field is '/'; on Microsoft Windows systems it is '\\'.
separator
The system-dependent default name-separator character, represented as a string for convenience.
pathSeparatorChar
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 ';'.
pathSeparator
The system-dependent path-separator character, represented as a string for convenience.



import java.io.*;
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","A.java");
            File f2 = new File("F:"+sc+"java"+sc+"hemraj"+sc+"Intro","A.java");
            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());
           
           
    }
}
output:
Paht f1= F:\java\hemraj\Intro\A.java
Paht f2= F:\java\hemraj\Intro\A.java
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 java.io 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.



















import java.io.*;


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.

import java.io.*;
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++)
        {
            System.out.println(i+"->"+str1[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++)
        {
            System.out.println(i+"->"+str2[i]);
        }
    }
}
Output:
List of files without filter
0->Directory.class
1->Directory.java
2->file.htm
3->file.java
4->FileHandle.class
5->FileHandle.java
6->FileTest.class
7->filter.class
8->FilterTest.class
9->FilterTest.java
10->io.doc
11->Marking.java
12->MyFilter.class
13->~$io.doc
List of files with filter
0->Directory.java
1->file.java
2->FileHandle.java
3->FilterTest.java
4->Marking.java

No comments:

Popular Posts