An example logic on getting and printing extension of a file in Java using String handling and Java IO.
Example
// Import for File class
import java.io.*;
class GetFileExt
{
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.
File[] files=f.listFiles();
// Loop till end of all files
for(int i=0;i<files.length;i++)
{
// Get the name of each file
String name=files[i].getName();
// File should not be a directory, and file should have an extension [this logic also filters folders containing .]
if(!files[i].isDirectory())
{
if(name.contains("."))
{
// Print the name of the file, and the extension
System.out.println("Extension for "+name+" is "+name.substring(name.lastIndexOf('.'),name.length()));
}
}
}
}
}
Main Logic
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.
Also see my other posts on Deleting all the files in a folder in Java, for help with lastIndexOf() method see my post lastIndexOf String and Character in Java Example
No comments:
Post a Comment