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.
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.
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
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With