我有一个文件名和扩展名列表。我想检查文件名是否以列表中的任何扩展名结尾。
String fileName = "abc.txt";
String[] extensions = {".txt", ".doc", ".pdf"};
我可以手动检查扩展名列表,并检查文件是否以列表中的任何扩展名结尾。
public static boolean checkIfFileHasExtension(String s, String[] extn) {
for (String entry : extn) {
if (s.endsWith(entry)) {
return true;
}
}
return false;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
String fileName = "abc.txt";
String[] extensions = {".txt", ".doc", ".pdf"};
System.out.println(checkIfFileHasExtension(fileName, extensions));
}
有没有更好的方法使用 StringUtils 或 Streams 或任何其他 Java 库来做到这一点?我正在寻找单线。谢谢!
尝试这个。
public static boolean checkIfFileHasExtension(String s, String[] extn) {
return Arrays.stream(extn).anyMatch(entry -> s.endsWith(entry));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)