568

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.

longda
  • 10,153
  • 7
  • 46
  • 66
  • 15
    You never know when some new platform is going to come along that defines extensions as being separated by a comma. Now you need to write platform dependent code. The Java frameworks should be more forward thinking and have APIs for getting extensions where they write the platform dependent code and you, as the user of the API, just say get the extension. – ArtOfWarfare Nov 19 '13 at 17:01
  • @ArtOfWarfare: OMG. Let's create a 100MB JRE with many thousands classes but please be sure to not implement any method which returns `"txt"` from `"filename.txt"` because some platform somewhere might want to use `"filename,txt"`. – Eric Duminil Nov 29 '19 at 12:54
  • @EricDuminil "Be sure to not implement any method which returns "txt" from "filename.txt"" ??? Try `path.substring(path.lastIndexOf("."));` ..... And yeah.. They are sure to don't duplicate something for nothing... – VelocityPulse Mar 17 '20 at 14:45
  • @VelocityPulse That's *exactly* what bothers me. Since there's no standard way to get the file extension, you get dozens of half-wrong answers and slightly different implementations. Your code uses 2 methods (I would have liked to have *one* single, explicit method), it returns `".txt"` from `"filename.txt"`, which might not be the desired result, and worst of all, it fails with `StringIndexOutOfBoundsException` instead of returning an empty string if there's no extension. – Eric Duminil Mar 17 '20 at 17:42
  • Finally, there is a new method `Path#getExtension` available right in the JDK as of Java 20: https://stackoverflow.com/a/74315488/3764965 – Nikolas Charalambidis Nov 04 '22 at 10:37

33 Answers33

741

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:

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.6</version>
</dependency>

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

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
Juan Rojas
  • 8,711
  • 1
  • 22
  • 30
  • 75
    Should be noted that it returns only "gz" for a file named archive.tar.gz. – Zitrax Apr 23 '14 at 11:38
  • 120
    @Zitrax that's because "gz" is the file extension. – BrainSlugs83 Apr 22 '15 at 04:44
  • 33
    @zhelon [.gz](https://en.wikipedia.org/wiki/Gzip) stands for gnu zipped file, and [.tar](https://en.wikipedia.org/wiki/Tar_(computing)) stands for (t)ape (ar)chive. So .tar.gz is a tar file inside a gnu zipped file, which has the .gz extension. – cirovladimir Mar 27 '16 at 16:35
  • is path neccessary as well ? – guru_001 Sep 13 '16 at 17:07
  • 2
    @guru_001 No it's not of course, it's just to mention that you may call it both with full path or just file name. – Scadge Oct 11 '16 at 15:04
  • 1
    @Zitrax can't have more than one extension for a file or extension name that contains dot, so in your case extension is .gz – user25 Feb 24 '18 at 18:01
  • This is the best solution because the getExtension() method is looking for the Last Separator in Unix and Windows systems. – Yash Aug 03 '22 at 16:17
370

Do you really need a "parser" for this?

String extension = "";

int i = fileName.lastIndexOf('.');
if (i > 0) {
    extension = fileName.substring(i+1);
}

Assuming that you're dealing with simple Windows-like file names, not something like archive.tar.gz.

Btw, for the case that a directory may have a '.', but the filename itself doesn't (like /path/to.a/file), you can do

String extension = "";

int i = fileName.lastIndexOf('.');
int p = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));

if (i > p) {
    extension = fileName.substring(i+1);
}
Tombart
  • 30,520
  • 16
  • 123
  • 136
EboMike
  • 76,846
  • 14
  • 164
  • 167
  • 4
    Thanks! Sure you might need a parser/object for this, if you wanted to do more manipulations than just the extension... say if you want just the path, the parent directory, the file name (minus the extension), etc. I'm coming from C# and .Net where we have this: http://msdn.microsoft.com/en-us/library/system.io.fileinfo_members.aspx – longda Aug 26 '10 at 00:31
  • 14
    As you say, there are a number of things to think about, beyond just using the naive lastIndexOf("."). I would guess that Apache Commons has a method for this, which takes all of the little tricky potential problems into account. – Tyler Aug 26 '10 at 00:46
  • 13
    I think `i > 0` should be changed to `i >= 0` or `i != -1`. This takes care of filenames like `.htaccess`. – Pijusn Jul 06 '13 at 15:50
  • 1
    New MSDN link from my comment above: http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx – longda Jan 02 '14 at 23:39
  • This solution will fail if the file extension contains a backslash. – foolo Sep 20 '14 at 22:03
  • 14
    regardless of how simple any code snippet is... you still need to update it/maintain it/test it/make it available as a convenient dependency... much easier if there was already a lib doing all of that – Don Cheadle Feb 13 '15 at 20:09
  • 2
    On more gotcha is if file endds with a dot. Better in a lib. if (i > p && i < (fileName.length()-1)) { extension = fileName.substring(i+1); – tgkprog Jul 06 '15 at 08:48
  • 1
    You should use `File.separatorChar` instead of `/` and `[backslash]`. – Dávid Horváth Apr 04 '16 at 13:22
  • `int i = filename.lastIndexOf('.')` gives a `dereferencing possible null pointer` warning on Netbeans. Why is that? – user1156544 May 30 '16 at 16:17
  • @user1156544 because if there is no `.` it will give a null pointer exception (another reason to use a library) – stackexchanger Aug 10 '17 at 19:54
  • "Do you really need a "parser" for this?" This is the type of question that occurs when Java (per usual) simply doesn't include the obvious things in the APIs. E.g. how about `new File(filename).getExtension()` -- that'd be cool. – Josh M. Aug 19 '22 at 23:46
111
private String getFileExtension(File file) {
    String name = file.getName();
    int lastIndexOf = name.lastIndexOf(".");
    if (lastIndexOf == -1) {
        return ""; // empty extension
    }
    return name.substring(lastIndexOf);
}
Radiodef
  • 37,180
  • 14
  • 90
  • 125
luke1985
  • 2,281
  • 1
  • 21
  • 34
  • 14
    Should be noted that this returns the '.' as well, so your file extension will be '.txt' as opposed to 'txt' in some of the other answers – NickEntin Nov 16 '14 at 22:25
  • 2
    Better Answer and @NickEntin Better comment. To remove the period "." from the extension of the file, can be coded as int lastIndexOf = name.lastIndexOf(".") + 1; – Hanzallah Afgan May 03 '15 at 05:30
  • 16
    that approach may not work in some case e.g. /usr/bin/foo.bar/httpconf – Iman Akbari Jul 16 '15 at 07:10
  • 8
    @lukasz1985 1. hundreds of linux packages make directories with names like "init.d", furthermore it's not safe to rely on the path not having directories with dots, since it's not illegal 2. I was coding for Android so I used some SDK method I don't remember but I guess http://stackoverflow.com/a/3571239/2546146 doesn't have this flaw – Iman Akbari Aug 04 '15 at 23:21
  • @luke1985 all GitHub's repos are finishing with .git but they actually are folders :) – Erdal G. Apr 14 '16 at 16:30
  • 6
    @Iman Akbari: getName() only returns the file name itself, which would be "httpconf" in your example. – Dreamspace President Jul 22 '17 at 10:30
  • 2
    You shouldn't rely on exceptions to guard against sloppy coding. Exception handling isn't required here. – intrepidis Feb 15 '18 at 01:35
  • [The edit which added `+ 1`](https://stackoverflow.com/revisions/21974043/4) inadvertently introduced an incorrect behavior when the file name has no extension. In a case like `"abc"` the method is supposed to return `""` but the edit made it incorrectly return `"abc"`. I rolled the answer back to Ilya's revision because it's the best example code and the answer's original author (who prefers exceptions for some reason) is inactive. – Radiodef Aug 09 '18 at 23:10
88

If you use Guava library, you can resort to Files utility class. It has a specific method, getFileExtension(). For instance:

String path = "c:/path/to/file/foo.txt";
String ext = Files.getFileExtension(path);
System.out.println(ext); //prints txt

In addition you may also obtain the filename with a similar function, getNameWithoutExtension():

String filename = Files.getNameWithoutExtension(path);
System.out.println(filename); //prints foo
Phani Rithvij
  • 4,030
  • 3
  • 25
  • 60
JeanValjean
  • 17,172
  • 23
  • 113
  • 157
  • 4
    Really? It is a great library, full of utilities. Most of them will be part of Java8, like the great Guava [Function](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Function.html). – JeanValjean Jun 12 '13 at 09:15
  • Not all people can decide which libraries to use, unfortunately. At least we have Apache Commons, albeit an old one. – Lluis Martinez Jan 30 '14 at 14:15
  • 1
    if you see the source code of `getFileExtension` actually it is just `int dotIndex = fileName.lastIndexOf('.'); return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1)` so not big deal. also, note that `Files` marked as "unstable" for some reason. – Al-Mothafar Jan 13 '19 at 12:27
  • 1
    @Al-Mothafar a lot of classes are marked as unstable (see multimap builders), I also don't understand why: several released have been made, but nothing has been changed there. – JeanValjean Jan 15 '19 at 12:12
27

If on Android, you can use this:

String ext = android.webkit.MimeTypeMap.getFileExtensionFromUrl(file.getName());
TWiStErRob
  • 44,762
  • 26
  • 170
  • 254
intrepidis
  • 2,870
  • 1
  • 34
  • 36
  • Note that this will not work if the string is not encoded(e.g. contains a space or a chinese character), see: https://stackoverflow.com/a/14321470/1074998 – 林果皞 Jan 24 '18 at 10:32
  • it is not getting extension other than English language – Ahmad Jun 10 '21 at 19:26
19

This is a tested method

public static String getExtension(String fileName) {
    char ch;
    int len;
    if(fileName==null || 
            (len = fileName.length())==0 || 
            (ch = fileName.charAt(len-1))=='/' || ch=='\\' || //in the case of a directory
             ch=='.' ) //in the case of . or ..
        return "";
    int dotInd = fileName.lastIndexOf('.'),
        sepInd = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
    if( dotInd<=sepInd )
        return "";
    else
        return fileName.substring(dotInd+1).toLowerCase();
}

And test case:

@Test
public void testGetExtension() {
    assertEquals("", getExtension("C"));
    assertEquals("ext", getExtension("C.ext"));
    assertEquals("ext", getExtension("A/B/C.ext"));
    assertEquals("", getExtension("A/B/C.ext/"));
    assertEquals("", getExtension("A/B/C.ext/.."));
    assertEquals("bin", getExtension("A/B/C.bin"));
    assertEquals("hidden", getExtension(".hidden"));
    assertEquals("dsstore", getExtension("/user/home/.dsstore"));
    assertEquals("", getExtension(".strange."));
    assertEquals("3", getExtension("1.2.3"));
    assertEquals("exe", getExtension("C:\\Program Files (x86)\\java\\bin\\javaw.exe"));
}
yavuzkavus
  • 1,268
  • 11
  • 17
18

If you use Spring framework in your project, then you can use StringUtils

import org.springframework.util.StringUtils;

StringUtils.getFilenameExtension("YourFileName")
Yiao SUN
  • 908
  • 1
  • 8
  • 26
16

In order to take into account file names without characters before the dot, you have to use that slight variation of the accepted answer:

String extension = "";

int i = fileName.lastIndexOf('.');
if (i >= 0) {
    extension = fileName.substring(i+1);
}

"file.doc" => "doc"
"file.doc.gz" => "gz"
".doc" => "doc"
Sylvain Leroux
  • 50,096
  • 7
  • 103
  • 125
16
String path = "/Users/test/test.txt";
String extension = "";

if (path.contains("."))
     extension = path.substring(path.lastIndexOf("."));

return ".txt"

if you want only "txt", make path.lastIndexOf(".") + 1

VelocityPulse
  • 613
  • 7
  • 13
12

My dirty and may tiniest using String.replaceAll:

.replaceAll("^.*\\.(.*)$", "$1")

Note that first * is greedy so it will grab most possible characters as far as it can and then just last dot and file extension will be left.

Ebrahim Byagowi
  • 10,338
  • 4
  • 70
  • 81
10

As is obvious from all the other answers, there's no adequate "built-in" function. This is a safe and simple method.

String getFileExtension(File file) {
    if (file == null) {
        return "";
    }
    String name = file.getName();
    int i = name.lastIndexOf('.');
    String ext = i > 0 ? name.substring(i + 1) : "";
    return ext;
}
intrepidis
  • 2,870
  • 1
  • 34
  • 36
10

Here is another one-liner for Java 8.

String ext = Arrays.stream(fileName.split("\\.")).reduce((a,b) -> b).orElse(null)

It works as follows:

  1. Split the string into an array of strings using "."
  2. Convert the array into a stream
  3. Use reduce to get the last element of the stream, i.e. the file extension
8

How about (using Java 1.5 RegEx):

    String[] split = fullFileName.split("\\.");
    String ext = split[split.length - 1];
Ninju Bohra
  • 460
  • 1
  • 5
  • 11
8

If you plan to use Apache commons-io,and just want to check the file's extension and then do some operation,you can use this,here is a snippet:

if(FilenameUtils.isExtension(file.getName(),"java")) {
    someoperation();
}
Geng Jiawen
  • 8,904
  • 3
  • 48
  • 37
8

Java 20 EA

As of Java 20 EA (early-access), there is finally a new method Path#getExtension that returns the extension as a String:

Paths.get("/Users/admin/notes.txt").getExtension();              // "txt"
Paths.get("/Users/admin/.gitconfig").getExtension();             // "gitconfig"
Paths.get("/Users/admin/configuration.xml.zip").getExtension();  // "zip"
Paths.get("/Users/admin/file").getExtension();                   // null
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
  • 1
    Actually this seems to have been bumped from 20 and moved to 21 potentially: https://bugs.openjdk.org/browse/JDK-8298303 – MrFlick Jan 06 '23 at 19:55
  • @MrFlick Interesting... but I don't understand why they decided to remove it from 20 if it was impactless and already there. – Nikolas Charalambidis Jan 14 '23 at 20:54
  • If you follow some of the threads you can there was disagreement as to what the return value should be. They took extra time to work out the details which meant they missed the deadline for 20. It looks like the version included in 21 will include the dot in the extension name. – MrFlick Jan 15 '23 at 18:59
4

Here's a method that handles .tar.gz properly, even in a path with dots in directory names:

private static final String getExtension(final String filename) {
  if (filename == null) return null;
  final String afterLastSlash = filename.substring(filename.lastIndexOf('/') + 1);
  final int afterLastBackslash = afterLastSlash.lastIndexOf('\\') + 1;
  final int dotIndex = afterLastSlash.indexOf('.', afterLastBackslash);
  return (dotIndex == -1) ? "" : afterLastSlash.substring(dotIndex + 1);
}

afterLastSlash is created to make finding afterLastBackslash quicker since it won't have to search the whole string if there are some slashes in it.

The char[] inside the original String is reused, adding no garbage there, and the JVM will probably notice that afterLastSlash is immediately garbage in order to put it on the stack instead of the heap.

Olathe
  • 1,885
  • 1
  • 15
  • 23
  • this method is copied from Guava source code you must mention this. – humazed May 31 '16 at 19:30
  • 1
    I didn't copy this. If it's in the Guava source code, they copied it from here. Perhaps notify them. – Olathe May 31 '16 at 19:33
  • sorry for that it's not identical btw, so may you and the Guava dev just has the same idea. – humazed May 31 '16 at 19:42
  • 2
    Really "gz" is the correct extension to return. If the calling code can also handle "tar" then it should additionally check, external to a `getExtension` function. If the user's file name is `"my zip. don't touch.tar.gz"` then this method will return the wrong extension. – intrepidis Feb 15 '18 at 01:43
4

How about JFileChooser? It is not straightforward as you will need to parse its final output...

JFileChooser filechooser = new JFileChooser();
File file = new File("your.txt");
System.out.println("the extension type:"+filechooser.getTypeDescription(file));

which is a MIME type...

OK...I forget that you don't want to know its MIME type.

Interesting code in the following link: http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html

/*
 * Get the extension of a file.
 */  
public static String getExtension(File f) {
    String ext = null;
    String s = f.getName();
    int i = s.lastIndexOf('.');

    if (i > 0 &&  i < s.length() - 1) {
        ext = s.substring(i+1).toLowerCase();
    }
    return ext;
}

Related question: How do I trim a file extension from a String in Java?

Community
  • 1
  • 1
eee
  • 1,043
  • 7
  • 5
4

This particular question gave me a lot of trouble then i found a very simple solution for this problem which i'm posting here.

file.getName().toLowerCase().endsWith(".txt");

That's it.

3
// Modified from EboMike's answer

String extension = "/path/to/file/foo.txt".substring("/path/to/file/foo.txt".lastIndexOf('.'));

extension should have ".txt" in it when run.

longda
  • 10,153
  • 7
  • 46
  • 66
3

How about REGEX version:

static final Pattern PATTERN = Pattern.compile("(.*)\\.(.*)");

Matcher m = PATTERN.matcher(path);
if (m.find()) {
    System.out.println("File path/name: " + m.group(1));
    System.out.println("Extention: " + m.group(2));
}

or with null extension supported:

static final Pattern PATTERN =
    Pattern.compile("((.*\\" + File.separator + ")?(.*)(\\.(.*)))|(.*\\" + File.separator + ")?(.*)");

class Separated {
    String path, name, ext;
}

Separated parsePath(String path) {
    Separated res = new Separated();
    Matcher m = PATTERN.matcher(path);
    if (m.find()) {
        if (m.group(1) != null) {
            res.path = m.group(2);
            res.name = m.group(3);
            res.ext = m.group(5);
        } else {
            res.path = m.group(6);
            res.name = m.group(7);
        }
    }
    return res;
}


Separated sp = parsePath("/root/docs/readme.txt");
System.out.println("path: " + sp.path);
System.out.println("name: " + sp.name);
System.out.println("Extention: " + sp.ext);

result for *nix:
path: /root/docs/
name: readme
Extention: txt

for windows, parsePath("c:\windows\readme.txt"):
path: c:\windows\
name: readme
Extention: txt

Dmytro Sokolyuk
  • 966
  • 13
  • 13
2

Here's the version with Optional as a return value (cause you can't be sure the file has an extension)... also sanity checks...

import java.io.File;
import java.util.Optional;

public class GetFileExtensionTool {

    public static Optional<String> getFileExtension(File file) {
        if (file == null) {
            throw new NullPointerException("file argument was null");
        }
        if (!file.isFile()) {
            throw new IllegalArgumentException("getFileExtension(File file)"
                    + " called on File object that wasn't an actual file"
                    + " (perhaps a directory or device?). file had path: "
                    + file.getAbsolutePath());
        }
        String fileName = file.getName();
        int i = fileName.lastIndexOf('.');
        if (i > 0) {
            return Optional.of(fileName.substring(i + 1));
        } else {
            return Optional.empty();
        }
    }
}
schuttek
  • 156
  • 1
  • 10
1
String extension = com.google.common.io.Files.getFileExtension("fileName.jpg");
Alfaville
  • 543
  • 7
  • 16
1

Here I made a small method (however not that secure and doesnt check for many errors), but if it is only you that is programming a general java-program, this is more than enough to find the filetype. This is not working for complex filetypes, but those are normally not used as much.

    public static String getFileType(String path){
       String fileType = null;
       fileType = path.substring(path.indexOf('.',path.lastIndexOf('/'))+1).toUpperCase();
       return fileType;
}
Rivalion
  • 19
  • 3
  • OP is looking for built-in method – Panther Jun 25 '15 at 03:13
  • (1) You should use `lastIndexOf` so file names like `john.smith.report.doc` are treated properly. (2) You should properly handle cases when there is no extension. This method returns `ABC/XYZ` for a path like `abc/xyz`, which doesn't make any sense. It would make more sense to return `""` or `null`. (3) [The file separator is not always `/`.](https://docs.oracle.com/javase/10/docs/api/java/io/File.html#separatorChar) – Radiodef Aug 09 '18 at 23:43
1

Getting File Extension from File Name

/**
 * The extension separator character.
 */
private static final char EXTENSION_SEPARATOR = '.';

/**
 * The Unix separator character.
 */
private static final char UNIX_SEPARATOR = '/';

/**
 * The Windows separator character.
 */
private static final char WINDOWS_SEPARATOR = '\\';

/**
 * The system separator character.
 */
private static final char SYSTEM_SEPARATOR = File.separatorChar;

/**
 * Gets the extension of a filename.
 * <p>
 * This method returns the textual part of the filename after the last dot.
 * There must be no directory separator after the dot.
 * <pre>
 * foo.txt      --> "txt"
 * a/b/c.jpg    --> "jpg"
 * a/b.txt/c    --> ""
 * a/b/c        --> ""
 * </pre>
 * <p>
 * The output will be the same irrespective of the machine that the code is running on.
 *
 * @param filename the filename to retrieve the extension of.
 * @return the extension of the file or an empty string if none exists.
 */
public static String getExtension(String filename) {
    if (filename == null) {
        return null;
    }
    int index = indexOfExtension(filename);
    if (index == -1) {
        return "";
    } else {
        return filename.substring(index + 1);
    }
}

/**
 * Returns the index of the last extension separator character, which is a dot.
 * <p>
 * This method also checks that there is no directory separator after the last dot.
 * To do this it uses {@link #indexOfLastSeparator(String)} which will
 * handle a file in either Unix or Windows format.
 * <p>
 * The output will be the same irrespective of the machine that the code is running on.
 *
 * @param filename  the filename to find the last path separator in, null returns -1
 * @return the index of the last separator character, or -1 if there
 * is no such character
 */
public static int indexOfExtension(String filename) {
    if (filename == null) {
        return -1;
    }
    int extensionPos = filename.lastIndexOf(EXTENSION_SEPARATOR);
    int lastSeparator = indexOfLastSeparator(filename);
    return (lastSeparator > extensionPos ? -1 : extensionPos);
}

/**
 * Returns the index of the last directory separator character.
 * <p>
 * This method will handle a file in either Unix or Windows format.
 * The position of the last forward or backslash is returned.
 * <p>
 * The output will be the same irrespective of the machine that the code is running on.
 *
 * @param filename  the filename to find the last path separator in, null returns -1
 * @return the index of the last separator character, or -1 if there
 * is no such character
 */
public static int indexOfLastSeparator(String filename) {
    if (filename == null) {
        return -1;
    }
    int lastUnixPos = filename.lastIndexOf(UNIX_SEPARATOR);
    int lastWindowsPos = filename.lastIndexOf(WINDOWS_SEPARATOR);
    return Math.max(lastUnixPos, lastWindowsPos);
}

Credits

  1. Copied from Apache FileNameUtils Class - http://grepcode.com/file/repo1.maven.org/maven2/commons-io/commons-io/1.3.2/org/apache/commons/io/FilenameUtils.java#FilenameUtils.getExtension%28java.lang.String%29
Vasanth
  • 6,257
  • 4
  • 26
  • 19
1

Without use of any library, you can use the String method split as follows :

        String[] splits = fileNames.get(i).split("\\.");

        String extension = "";

        if(splits.length >= 2)
        {
            extension = splits[splits.length-1];
        }
Farah
  • 2,469
  • 5
  • 31
  • 52
1
    private String getExtension(File file)
        {
            String fileName = file.getName();
            String[] ext = fileName.split("\\.");
            return ext[ext.length -1];
        }
0

Just a regular-expression based alternative. Not that fast, not that good.

Pattern pattern = Pattern.compile("\\.([^.]*)$");
Matcher matcher = pattern.matcher(fileName);

if (matcher.find()) {
    String ext = matcher.group(1);
}
shapiy
  • 1,117
  • 12
  • 14
0

I like the simplicity of spectre's answer, and linked in one of his comments is a link to another answer that fixes dots in file paths, on another question, made by EboMike.

Without implementing some sort of third party API, I suggest:

private String getFileExtension(File file) {

    String name = file.getName().substring(Math.max(file.getName().lastIndexOf('/'),
            file.getName().lastIndexOf('\\')) < 0 ? 0 : Math.max(file.getName().lastIndexOf('/'),
            file.getName().lastIndexOf('\\')));
    int lastIndexOf = name.lastIndexOf(".");
    if (lastIndexOf == -1) {
        return ""; // empty extension
    }
    return name.substring(lastIndexOf + 1); // doesn't return "." with extension
}

Something like this may be useful in, say, any of ImageIO's write methods, where the file format has to be passed in.

Why use a whole third party API when you can DIY?

DDPWNAGE
  • 1,423
  • 10
  • 37
0

The fluent way:

public static String fileExtension(String fileName) {
    return Optional.of(fileName.lastIndexOf(".")).filter(i-> i >= 0)
            .filter(i-> i > fileName.lastIndexOf(File.separator))
            .map(fileName::substring).orElse("");
}
Nolle
  • 201
  • 2
  • 5
-1

try this.

String[] extension = "adadad.adad.adnandad.jpg".split("\\.(?=[^\\.]+$)"); // ['adadad.adad.adnandad','jpg']
extension[1] // jpg
Adnane
  • 1
-1
  @Test
    public void getFileExtension(String fileName){
      String extension = null;
      List<String> list = new ArrayList<>();
      do{
          extension =  FilenameUtils.getExtension(fileName);
          if(extension==null){
              break;
          }
          if(!extension.isEmpty()){
              list.add("."+extension);
          }
          fileName = FilenameUtils.getBaseName(fileName);
      }while (!extension.isEmpty());
      Collections.reverse(list);
      System.out.println(list.toString());
    }
Ashish Pancholi
  • 4,569
  • 13
  • 50
  • 88
-1

I found a better way to find extension by mixing all above answers

public static String getFileExtension(String fileLink) {

        String extension;
        Uri uri = Uri.parse(fileLink);
        String scheme = uri.getScheme();
        if (scheme != null && scheme.equals(ContentResolver.SCHEME_CONTENT)) {
            MimeTypeMap mime = MimeTypeMap.getSingleton();
            extension = mime.getExtensionFromMimeType(CoreApp.getInstance().getContentResolver().getType(uri));
        } else {
            extension = MimeTypeMap.getFileExtensionFromUrl(fileLink);
        }

        return extension;
    }

public static String getMimeType(String fileLink) {
        String type = CoreApp.getInstance().getContentResolver().getType(Uri.parse(fileLink));
        if (!TextUtils.isEmpty(type)) return type;
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        return mime.getMimeTypeFromExtension(FileChooserUtil.getFileExtension(fileLink));
    }
Raghav Satyadev
  • 728
  • 2
  • 11
  • 38
-4

Java has a built-in way of dealing with this, in the java.nio.file.Files class, that may work for your needs:

File f = new File("/path/to/file/foo.txt");
String ext = Files.probeContentType(f.toPath());
if(ext.equalsIgnoreCase("txt")) do whatever;

Note that this static method uses the specifications found here to retrieve "content type," which can vary.

Nick Giampietro
  • 178
  • 1
  • 8
  • 28
    This is incorrect. The return type for probeContentType is the Mime content type, not the file extension. It will usually not match the extension. This would also be pretty slow in a file browser, since it actually opens the file to determine the type. – Charles Nov 08 '13 at 01:00