Hire us for all your ICT Issues (Facebook ads,Web Development,CCTV,Programming and Many More)

HowTo Display The Information Of File Using Java

In this article we are going to demonstrate how to display the information of the file in the java programming.
Java program that reads a file name from the user and then displays information about whether the file exists, whether the file is readable/writable, the type of file and the length of the file in bytes and display the content using FileInputStream.

import java.io.*;
import javax.swing.*;
class FileDemo
{
 public static void main(String args[])
 {
  String filename = JOptionPane.showInputDialog("Enter filename: ");
  File f = new File(filename);
  System.out.println("File exists: "+f.exists());
  System.out.println("File is readable: "+f.canRead());
  System.out.println("File is writable: "+f.canWrite());
  System.out.println("Is a directory: "+f.isDirectory());
  System.out.println("length of the file: "+f.length()+" bytes");
  
  try
  {
   char ch;
   StringBuffer buff = new StringBuffer("");
   FileInputStream fis = new FileInputStream(filename);
   while(fis.available()!=0)
   {
    ch = (char)fis.read();
    buff.append(ch);
   }
   System.out.println("\nContents of the file are: ");
   System.out.println(buff);
   fis.close();
  }
  catch(FileNotFoundException e)
  {
   System.out.println("Cannot find the specified file...");
  }
  catch(IOException i)
  {
   System.out.println("Cannot read file...");
  }
 }
}
Input and output for the above program is as follows:
File name: sample.txt
File exists: true
File is readable: true
File is writable: true
Is a directory: false
length of the file: 20 bytes
Contents of the file are:
Hi, welcome to Java.
Take your time to comment on this article.
SHARE

Aone Abu Ukaasha

Hi. I’m Designer of F@stest Vpn. I’m CEO/Founder of Technocrat. I’m a Programmer, Web Designer,Engineer,System Analyst,Crypt Networking Admin,Web Developer, Business Enthusiast,Networking Marketer,Apps Developer." No answer has ever been made without a querry"

  • Image
  • Image
  • Image
  • Image
  • Image
    Blogger Comment
    Facebook Comment