Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

file

io

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.

like image 708
longda Avatar asked Aug 26 '10 00:08

longda


People also ask

How do I save a Java file extension?

Saving a Java Program Java programs must be saved in a file whose name ends with the . java extension, so using your favorite ASCII editor, enter the program exactly as it appears on the first page of this lesson and save the program to a file named DateApp.


2 Answers

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

like image 60
Juan Rojas Avatar answered Nov 12 '22 22:11

Juan Rojas


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); } 
like image 23
EboMike Avatar answered Nov 13 '22 00:11

EboMike