简体   繁体   中英

JAVA - Most efficient way to remove file extension

I want remove the extension of a file. For example:

  • ActualFile = image.png
  • ExpectedFile = image

Which method is the most efficient to use?

  1. removeExtension() method provided by org.apache.commons.io
  2. fileName.substring(0, fileName.lastIndexOf('.'))

No difference, except one. Do you really want to add whole Apache lib to use only one method? If you use Apache in your application - then use it as well. If not - do create your custom implementation - this is not a rocket-science.

Looking at removeExtension from commons-io you can see that substring is also used underwater in that method in a similar way you describe:

public static String removeExtension(final String fileName) {
    if (fileName == null) {
        return null;
    }
    failIfNullBytePresent(fileName);

    final int index = indexOfExtension(fileName);
    if (index == NOT_FOUND) {
        return fileName;
    }
    return fileName.substring(0, index);
}

Your method is faster since there are less operations being done, but the removeExtension method has the failIfNullBytePresent which states:

Check the input for null bytes, a sign of unsanitized data being passed to to file level functions.

This may be used for poison byte attacks.

and indexOfExtension to get the index of the extension which has more checks (as you can see in the javadoc of that method here ).

Conclusion

Your method is faster but I'd say using the commons-io is safer/more consistent in various situations, but what to use depends on how complex your situation is whether it's a critical feature of an application or just a home made project for yourself. removeExtension is not that complex or slow that you shouldn't use it perse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM