Thursday 24 May 2012

Load a file in Java

The following code shows how to load a file in Java using java.io.File class and retrieve the file attributes.




import java.io.File;

class LoadFile {

    public static void main(String args[]) {

        File file = new File("/home/radhakrishnan/t1.txt");

        System.out.println("Is File exists : " + file.exists());
        System.out.println("Is Directory : " + file.isDirectory());
        System.out.println("Is File : " + file.isFile());
        System.out.println("Is hidden file : " + file.isHidden());
        System.out.println("Absolute Path : " + file.getAbsolutePath());
        System.out.println("Parent : " + file.getParent());
        System.out.println("Path : " + file.getPath());
        System.out.println("FileName : " + file.getName());
        System.out.println("Last Modified : " + file.lastModified());
        System.out.println("File Length(in bytes) : " + file.length());
        System.out.println("Can Read : " + file.canRead());
        System.out.println("Can Write : " + file.canWrite());
        System.out.println("Can Execute : " + file.canExecute());

    }

}

Recursively list files in Java

We can use java.io.File class for recursively listing all files under a directory in Java. A File class object is an abstract representation of file and directory pathnames.

new File("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. 

The java.io.File class provides many methods for getting information about a file system. Please visit Load a file in Java to learn more about it.


We can use File class listFiles() method for listing all the files and directories under a given directory (Note: This method won't recursively list files).


File f=new File("pathname");
File[]list=f.listFiles();