Written by Sai Sameera Thota on September 19, 2013 in Java > Programming

Java Program to get File Information

GET ALERTS:

Get our Latest updates delivered to your mailbox!

Problem:
Write a Java program that reads a file from the user then and display the information about whether that file exists, whether the file is readable, writable, the type of file and the length of the file in bytes. The program uses conditional operator to check different functionalities of the given file.

Solution:

Java Program to get File Information

import java.io.*;
public class FileInfo
{

	public static void main(String[] args) throws IOException
	{

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.print("\nEnter A File Name:");
		String fName = br.readLine();

		File f = new File(fName);

        /*The method exists() checks whether the given file exists in the current directory or not.
		The method returns a boolean value*/
		String result = f.exists() ? "exists." : "does not exist.";
		System.out.println("\nThe given file " + result);
		if(f.exists())
		{
			//The method canRead() checks whether the file is readable or not readable and returns a boolean value
			result = f.canRead() ? "readable." : "not readable.";
			System.out.println("The given file is " + result);

			//The method canWrite() checks whether the given file is writable or not and returns a boolean value
			result = f.canWrite() ? "writable." : "not writable.";
			System.out.println("The given file is " + result);

            //The method length() returns the length of the given file in bytes
			System.out.println("The given file length is " + f.length() + " in bytes.");

			/*
			  If the filename ends with .jpg,.gif or .png, the given file is an image file
			  If the filename ends with .exe or .txt, the given file is an executable file or a text file respectively
			  else the file type is unknown. 
			  The method endsWith() returns true if the given string ends with the string given as argument for the method else
			  it returns false
			*/
 
			if (fName.endsWith(".jpg") || fName.endsWith(".gif") || fName.endsWith(".png"))
			{
				System.out.println("The given file is an image file.");
			}
			else if (fName.endsWith(".exe"))
			{
				System.out.println("The given file is an executable file.");
			}
			else if (fName.endsWith(".txt"))
			{	
				System.out.println("The given file is a text file.");
			}
			else
			{
				System.out.println("The file type is unknown.");
			}
		}
	}
}

Output:
Java Program to get File Information

Download Source Code

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: