Code for File Extension
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
/////////////////////////////////////////