Home >Java >javaTutorial >How to Efficiently Retrieve File Extensions in Java?
Retrieving File Extensions in Java
Obtaining the file extension of a given file in Java is a common task. To achieve this without creating custom parsers, there are several built-in methods available.
Using FilenameUtils.getExtension from Apache Commons IO
The Apache Commons IO library offers a convenient method, FilenameUtils.getExtension, to extract file extensions. It can be used as follows:
import org.apache.commons.io.FilenameUtils; // ... String ext1 = FilenameUtils.getExtension("/path/to/file/foo.txt"); // "txt" String ext2 = FilenameUtils.getExtension("bar.exe"); // "exe"
Maven Dependency
To use FilenameUtils.getExtension, you can include the following dependency in your Maven project:
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency>
Gradle Dependencies
For Gradle Groovy DSL and Kotlin DSL, the dependencies are as follows:
Groovy DSL
implementation 'commons-io:commons-io:2.6'
Kotlin DSL
implementation("commons-io:commons-io:2.6")
For other dependency management systems, please refer to Maven Central:
https://search.maven.org/artifact/commons-io/commons-io/2.6/jar
The above is the detailed content of How to Efficiently Retrieve File Extensions in Java?. For more information, please follow other related articles on the PHP Chinese website!