springboot判断是PDF文件还是图片的if语句再嵌套一个是否为空的if语句完整代码
时间: 2023-05-14 19:05:34 浏览: 159
以下是一个简单的示例代码,用于判断给定文件是否为PDF文件或图片文件:
```
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
public class FileTypeChecker {
public static void main(String[] args) {
File file = new File("path/to/file");
try {
String fileType = Files.probeContentType(file.toPath());
if (fileType != null && fileType.startsWith("image")) {
System.out.println("This is an image file.");
} else if (fileType != null && fileType.equals("application/pdf")) {
System.out.println("This is a PDF file.");
} else {
System.out.println("This is neither an image nor a PDF file.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
该代码使用 `Files.probeContentType()` 方法来检查文件的 MIME 类型,然后根据 MIME 类型判断文件类型。如果 MIME 类型以 "image" 开头,则文件为图片文件;如果 MIME 类型为 "application/pdf",则文件为 PDF 文件。如果 MIME 类型为其他类型,则文件既不是图片文件也不是 PDF 文件。
注意:该代码仅适用于检查文件类型,不适用于检查文件内容是否为 PDF 或图片。