Java Program to Display File Information

Java program to display file information. Write a java program which accepts a string as command line argument and checks whether the string is file or a directory. If it is a file it displays all the information about the file such as file name, last modified date and time, file size, file path, absolute path, parent directory, is the file readable?, is the file writable?, is the file hidden? etc. and if it a directory it displays all the files in that directory.

Java Program to Display File Information

Here is the source code of java program to display information of given file.
import java.io.*;

class DisplayFileInformation{

 public static void main(String args[])
 {
  String Filename = args[0];

  File f1 = new File(Filename);

  if(f1.isFile())
  {
   System.out.println("File Name: "  + f1.getName());
   System.out.println("File last modified: " + f1.lastModified());
   System.out.println("File Size: " + f1.length() + " Bytes");
   System.out.println("File Path: " + f1.getPath());
   System.out.println("Absolute Path: " + f1.getAbsolutePath());
   System.out.println("Parent: " + f1.getParent());
   System.out.println(f1.canWrite() ? "File is writable" : "File is not writable");
   System.out.println(f1.canRead() ? "File is readable" : "File is not readable");
   System.out.println(f1.isHidden() ? "File is hidden" :  "File is not hidden");
  }
  else if(f1.isDirectory())
  {
   System.out.println("Contents of " + Filename + " directory are: ");

   int count = 0;
   String[] s = f1.list();

   for(String str: s)
   {
    File f = new File(Filename,str);
    if(f.isFile())
     count++;
   }

   System.out.println("There are " + count + " Files in given directory. Subdirectories not considered.");
  }
 }
}

Output:

/* Output of above code:

Sample Output 1:
Contents of SEM2 directory are: 
There are 0 Files in given directory. Subdirectories not considered.

Sample Output 2:
File Name: Ass5SetA1.java
File last modified: 1581164328000
File Size: 1144 Bytes
File Path: Ass5SetA1.java
Absolute Path: /home/abhijitkokane/JAVA/Ass5SetA1.java
Parent: null
File is writable
File is readable
File is not hidden

*/

Comments