HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaCritical

How do I get the file extension of a file in Java?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howextensionjavathefileget

Problem

Just to be clear, I'm not looking for the MIME type.

Let's say I have the following input: /path/to/file/foo.txt

I'd like a way to break this input up, specifically into .txt for the extension. Is there any built in way to do this in Java? I would like to avoid writing my own parser.

Solution

In this case, use FilenameUtils.getExtension from Apache Commons IO

Here is an example of how to use it (you may specify either full path or just file name):

import org.apache.commons.io.FilenameUtils;

// ...

String ext1 = FilenameUtils.getExtension("/path/to/file/foo.txt"); // returns "txt"
String ext2 = FilenameUtils.getExtension("bar.exe"); // returns "exe"


Maven dependency:


  commons-io
  commons-io
  2.6


Gradle Groovy DSL

implementation 'commons-io:commons-io:2.6'


Gradle Kotlin DSL

implementation("commons-io:commons-io:2.6")


Others https://search.maven.org/artifact/commons-io/commons-io/2.6/jar

Code Snippets

import org.apache.commons.io.FilenameUtils;

// ...

String ext1 = FilenameUtils.getExtension("/path/to/file/foo.txt"); // returns "txt"
String ext2 = FilenameUtils.getExtension("bar.exe"); // returns "exe"
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.6</version>
</dependency>
implementation 'commons-io:commons-io:2.6'
implementation("commons-io:commons-io:2.6")

Context

Stack Overflow Q#3571223, score: 756

Revisions (0)

No revisions yet.