Define the Main Method
In this step, we will define the main method to accept a filename from the user and extract its extension.
import java.io.IOException;
public class FileExtension {
public static void main(String[] args) throws IOException {
if (args.length > 0) {
String filename = args[0];
int index = filename.lastIndexOf(".");
if (index > 0) {
String extension = filename.substring(index + 1);
System.out.println("File extension: " + extension);
} else {
System.out.println("No file extension found");
}
} else {
System.out.println("Please provide a filename");
}
}
}
In the above code block, we are checking if a filename is provided by the user. If no filename is provided, it will prompt the user to provide a filename. We then use the lastIndexOf()
method to get the index of the last dot in the filename which marks the beginning of the extension. If no dot is found in the filename, it suggests that the file has no extension. In both cases, we inform the user through command line output.