Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What's the most efficient way to trim the suffix in Java, like this:

title part1.txt title part2.html => title part1 title part2 
like image 305
omg Avatar asked Jun 02 '09 18:06

omg


People also ask

How to remove extension from String in Java?

Use Apache Commons IO, FilenameUtils. getBaseName(String filename) or removeExtension(String filename) , if you need the path too. Show activity on this post. Gracefully handles null , cases where there is nothing that looks like an extension and doesn't molest files that start with a . , this also handles the .

How to get the filename without the extension in Java?

Using Regex\w+$ with the replaceAll() method that removes the last dot and all the characters that follow it. That's all about getting the filename without extension in Java.

How can I find the file name without extension?

GetFileNameWithoutExtension(ReadOnlySpan<Char>) Returns the file name without the extension of a file path that is represented by a read-only character span.

How do I crop a string in Java?

The trim() method in Java String is a built-in function that eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.


2 Answers

This is the sort of code that we shouldn't be doing ourselves. Use libraries for the mundane stuff, save your brain for the hard stuff.

In this case, I recommend using FilenameUtils.removeExtension() from Apache Commons IO

like image 88
skaffman Avatar answered Oct 08 '22 10:10

skaffman


str.substring(0, str.lastIndexOf('.')) 
like image 44
Svitlana Maksymchuk Avatar answered Oct 08 '22 09:10

Svitlana Maksymchuk