简体   繁体   English

JAVA-删除文件扩展名的最有效方法

[英]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 org.apache.commons.io提供的removeExtension()方法
  2. fileName.substring(0, fileName.lastIndexOf('.'))

No difference, except one. 没有区别,只有一个。 Do you really want to add whole Apache lib to use only one method? 您是否真的要添加整个Apache库以仅使用一种方法? If you use Apache in your application - then use it as well. 如果您在应用程序中使用Apache-那么也要使用它。 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: commons-io中查看removeExtension ,您可以看到substring也以与您描述的相似方式在水下用于该方法:

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: 因为执行的操作较少,所以您的方法更快,但是removeExtension方法具有failIfNullBytePresent ,它指出:

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 ). indexOfExtension来获取具有更多检查的扩展的索引(如您在此处的该方法的javadoc中所看到的 )。

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. 您的方法更快,但是我想说在各种情况下使用commons-io更为安全/一致,但是使用哪种方法取决于您的情况是否复杂,这是应用程序的关键功能还是自己的自制项目。 removeExtension is not that complex or slow that you shouldn't use it perse. removeExtension 不是复杂或缓慢的,你不应该深灰色使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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