在Java中,可以通过检查文件扩展名来获取文件的MIME类型。以下是一个简单的示例,展示了如何根据文件扩展名获取MIME类型:
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
public class MimeTypeDetector {
private static final Map<String, String> MIME_TYPES = new HashMap<>();
static {
MIME_TYPES.put("txt", "text/plain");
MIME_TYPES.put("html", "text/html");
MIME_TYPES.put("css", "text/css");
MIME_TYPES.put("js", "application/javascript");
MIME_TYPES.put("json", "application/json");
MIME_TYPES.put("png", "image/png");
MIME_TYPES.put("jpg", "image/jpeg");
MIME_TYPES.put("jpeg", "image/jpeg");
MIME_TYPES.put("gif", "image/gif");
MIME_TYPES.put("bmp", "image/bmp");
MIME_TYPES.put("pdf", "application/pdf");
MIME_TYPES.put("doc", "application/msword");
MIME_TYPES.put("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
MIME_TYPES.put("xls", "application/vnd.ms-excel");
MIME_TYPES.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
MIME_TYPES.put("ppt", "application/vnd.ms-powerpoint");
MIME_TYPES.put("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
MIME_TYPES.put("mp3", "audio/mpeg");
MIME_TYPES.put("mp4", "video/mp4");
MIME_TYPES.put("avi", "video/x-msvideo");
MIME_TYPES.put("flv", "video/x-flv");
MIME_TYPES.put("3gp", "video/3gpp");
MIME_TYPES.put("mkv", "video/x-matroska");
MIME_TYPES.put("wmv", "video/x-ms-wmv");
}
public static void main(String[] args) throws IOException {
String filePath = "path/to/your/file";
String mimeType = getMimeType(filePath);
System.out.println("MIME type of the file: " + mimeType);
}
public static String getMimeType(String filePath) throws IOException {
Path path = Paths.get(filePath);
String extension = Files.probeContentType(path);
if (extension == null) {
extension = filePath.substring(filePath.lastIndexOf(".") + 1);
}
return MIME_TYPES.getOrDefault(extension.toLowerCase(), "application/octet-stream");
}
}
这个示例中,我们使用了一个静态的HashMap来存储文件扩展名和MIME类型之间的映射。在getMimeType
方法中,我们首先尝试使用Java的Files.probeContentType
方法来获取文件的MIME类型。如果这个方法返回null,我们将使用文件扩展名作为键来查找MIME类型。如果找不到对应的MIME类型,我们将返回"application/octet-stream"作为默认类型。
请注意,这个示例仅支持一些常见的MIME类型。如果您需要支持更多的MIME类型,请扩展MIME_TYPES
映射。
领取专属 10元无门槛券
手把手带您无忧上云