Saturday, August 22, 2009

Java Code for File Extension

Hi friends, Java Code Online welcomes you back again. The last post I have made was for getting the file name without the extension of the file. But there are many scenarios when we desire the extension of the file, and not the name of the file.

The Java code here asks the user to enter a valid file name, and then remove the file name but keep the extension of it. So the user enters a file name and gets the extension of it.

The Java Code is provided below:-

///////////////////////////////////
package developer;

import java.util.Scanner;

public class FileExtension {

/**
* @param args
*/
public static void main(String[] args) {

String fileExt = null;

System.out.println("Enter a valid file name whose extension is desired:");

Scanner scan = new Scanner(System.in);

if(scan.hasNext())
{
fileExt = getFileExtension(scan.next());
}

if(null != fileExt)
{
System.out.println("The extension of the file is: "+fileExt);
}
else
{
System.out.println("Not a valid file name");
}

}

//get the file extension of the file entered
public static String getFileExtension(String filePath)
{
String extension = null;
if(null != filePath && filePath.contains("."))
{
extension = filePath.substring(filePath.lastIndexOf("."), filePath.length());
}
return extension;
}

}

////////////////////////////////////////

When this code is executed, the output is something like as given below:-

//////////////////////////////////////////
Output

Enter a valid file name whose extension is desired:
javadeveloper.java
The extension of the file is: .java
/////////////////////////////////////////

I hope the article was helpful, and my efforts did not went in vain. Keep ticking Java Code Online for more Java details.

Other article of interest:-
Remove the extension from the filename

1 comment:

  1. Very good Information for Students !!!

    Any one wants to know more about Java !!!

    Please visit http://www.javacircuit.blogspot.com

    ReplyDelete

Note: Only a member of this blog may post a comment.