Java Program to list all files of a directory with details size, modified date, filename

The following code lists all the files and directories of a directory which is accepted through command line prompt. The program lists files with details like date modified, Directory or File (if directory then prints <DIR> otherwise blank) , size of the file and file name. For doing the above task, i have used various useful methods of File Class like isDirectory(), listFiles(), length(), getAbsolutePath(), lastModified(), getName() which will make you more familiar in these methods. Brief description of the methods used in the program only is as follows.

File : File object represents a pathname to a physical file or directory in the hard disk. It creates a new File instance by converting the given pathname string into an abstract pathname.

isDirectory():Returns true if the file denoted by this abstract pathname is a directory .

listFiles() : Returns an array of File objects for the files and directories located in the directory .

length() : Returns the length of the file in bytes. If the current File object represents a directory , then 0 (zero) is returned. Output type is long.

getAbsolutePath(): Returns an abosolute path for the file or directory represented by current File object.

lastModified() : Returns a long which represents the time that the file was last modified

getName() : Returns the name of the file without path.

The below program outputs as DateModified &lt;DIR&gt; / Blank FileSize FileName which is almost similar to dir command in dos . Limitation is , it lists the files only for the given directory not for subdirectories and it does not display the modified time.

 

Running the program will output as follows

You may also like

Leave a Reply