Get Extension of a File in Java
An example logic on getting and printing extension of a file in Java using String handling and Java IO.
// Import for File class
public static void main(String args)
// Create a file object for directory C:\java
File f=new File("C:/java");
// List all the files in the directory, get their File objects.
// Loop till end of all files
// Get the name of each file
// File should not be a directory, and file should have an extension [this logic also filters folders containing .]
// Print the name of the file, and the extension
System.out.println("Extension for "+name+" is "+name.substring(name.lastIndexOf('.'),name.length()));
lastIndexOf('.'): This method present in the String class returns the last index of the character '.'. For example, if a file name is like file.n.ex then the lastIndexOf('.') will return, 6 but not 4. It is obvious.
substring(name.lastIndexOf('.'),name.length()): The substring method present in the String class, takes start and end positions as parameters, this method returns a string between the start and end parameters. Here, name consists of extension too. So, the last index of '.' is the first (start) parameter and name.length() means end of the string is the end parameter. So, it is obvious that the extension is filtered.