Java 判断文件格式是否为图片 - 使用 String.endsWith() 方法
使用 Java 中的 String 类的 endsWith() 方法可以判断文件的后缀名是否为图片格式。以下是一个示例代码:
import java.io.File;
public class FileFormatChecker {
public static void main(String[] args) {
String filePath = "path/to/file.jpg";
boolean isImage = isImageFile(filePath);
if (isImage) {
System.out.println("文件是图片格式");
} else {
System.out.println("文件不是图片格式");
}
}
public static boolean isImageFile(String filePath) {
String[] imageExtensions = { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
File file = new File(filePath);
String fileName = file.getName();
for (String extension : imageExtensions) {
if (fileName.toLowerCase().endsWith(extension)) {
return true;
}
}
return false;
}
}
在示例代码中,isImageFile() 方法接收一个文件路径作为参数,并通过遍历图片格式的后缀名数组,判断文件的后缀名是否为图片格式。如果后缀名匹配任一图片格式,则返回 true,否则返回 false。
你可以将 filePath 替换为你要检查的文件路径,然后调用 isImageFile() 方法来判断文件是否为图片格式。如果返回值为 true,则说明文件是图片格式,否则不是图片格式。
原文地址: https://www.cveoy.top/t/topic/pJBs 著作权归作者所有。请勿转载和采集!