How do I get the file extension of a file in Java?
To get the file extension of a file in Java, you can use the File
class and its getName()
method to get the file name, and then use the substring()
method of the String
class to extract the extension from the file name.
Here is an example of how you can do this:
import java.io.File;
// ...
// Get the file object
File file = new File("/path/to/file.txt");
// Get the file name
String fileName = file.getName();
// Extract the extension from the file name
int index = fileName.lastIndexOf('.');
if (index > 0) {
String extension = fileName.substring(index+1);
System.out.println(extension);
}
This will print the file extension (e.g. "txt") to the console.
Note that this method will only work if the file name includes the extension, and if the extension is separated from the rest of the file name by a '.' character. If the file name does not include the extension, or if the extension is not separated from the rest of the file name by a '.' character, this method will not work correctly.
You can also use the FileNameUtils.getExtension()
method of the Apache Commons IO library to get the file extension. This method is more robust and handles a wider range of file names and extensions. Here is an example of how to use it:
import org.apache.commons.io.FileNameUtils;
// ...
// Get the file object
File file = new File("/path/to/file.txt");
// Get the file name
String fileName = file.getName();
// Get the file extension
String extension = FileNameUtils.getExtension(fileName);
System.out.println(extension);
This will also print the file extension (e.g. "txt") to the console.