java获取一个文件的文件类型
时间: 2023-06-05 07:05:42 浏览: 182
可以使用Java中的文件类型探测器(FileTypeDetector)类来获取文件的类型。FileTypeDetector类提供了一种机制来检查文件的类型,并返回文件的MIME类型。以下是查找文件类型的示例代码:
```java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.spi.FileTypeDetector;
public class FileTypeDemo {
public static void main(String[] args) throws IOException {
// specify the file path of the file whose file type needs to be obtained
Path path = Paths.get("path/to/file");
// create FileTypeDetector object
FileTypeDetector fileTypeDetector = new MyFileTypeDetector();
// get file type
String mimeType = fileTypeDetector.probeContentType(path);
System.out.println("File type: " + mimeType);
}
}
class MyFileTypeDetector extends FileTypeDetector {
@Override
public String probeContentType(Path path) throws IOException {
return Files.probeContentType(path);
}
}
```
在上述代码中,probeContentType()方法可以返回文件的MIME类型。对于未知类型的文件,该方法将返回null。