输出啊
1、添加pom依赖
<properties><java.version>1.8</java.version><tika.version>1.26</tika.version><jmimemagic.version>0.1.5</jmimemagic.version></properties> <!-- 文件类型检测 --><dependency><groupId>org.apache.tika</groupId><artifactId>tika-core</artifactId><version>${tika.version}</version></dependency><dependency><groupId>org.apache.tika</groupId><artifactId>tika-parsers</artifactId><version>${tika.version}</version></dependency><dependency><groupId>net.sf.jmimemagic</groupId><artifactId>jmimemagic</artifactId><version>${jmimemagic.version}</version></dependency>
2、实现代码
/*** 获取文件后缀** @param fileContent 文件内容* @return java.lang.String* @author demo* @since 2024/1/30 14:06**/private String getFileExtension(byte[] fileContent) {InputStream is = new ByteArrayInputStream(fileContent);AutoDetectParser parser = new AutoDetectParser();Metadata metadata = new Metadata();org.apache.tika.mime.MediaType mediaType;try {ContentHandler handler = new BodyContentHandler();parser.parse(is, handler, metadata);mediaType = org.apache.tika.mime.MediaType.parse(metadata.get(HttpHeaders.CONTENT_TYPE));TikaConfig tikaConfig = TikaConfig.getDefaultConfig();MimeTypes allTypes = tikaConfig.getMimeRepository();return allTypes.forName(mediaType.toString()).getExtension();} catch (Exception e) {try {MagicMatch match = Magic.getMagicMatch(fileContent);return "." + match.getExtension();} catch (Exception e1) {log.error("getFileType error", e);}return null;}}
3、测试效果
测试本地文件类型和后缀
public static void main(String[] args) throws Exception {List<File> files = FileUtil.loopFiles("C:\\Users\\liubei\\Downloads\\test");for (File file : files) {byte[] fileContent = FileUtil.readBytes(file);try {String extension = getFileExtension(fileContent);System.out.println("fileName:" + file.getName() + ",fileExtension:" + extension);} catch (Exception e) {e.printStackTrace();}}}
输出结果
MagicMatch fileName:testing-with-spock.pdf,getExtension:pdf
fileName:Marelli - 0919.xls,fileExtension:.xls
fileName:R-C.gif,fileExtension:.gif
fileName:R-C.jfif,fileExtension:.jpg
fileName:rose-blue-flower-rose-blooms-67636.jpeg,fileExtension:.jpg
fileName:txtTest.txt,fileExtension:
fileName:1c7b5b29262f292c64_hd.jpg,fileExtension:.jpg
MagicMatch fileName:软件架构设计_PreE4_V0.1.docx,getExtension:docx
fileName:5W2H分析法培训教材.ppt,fileExtension:.ppt
fileName:新建 Microsoft Excel 工作表.xlsx,fileExtension:.xlsx
fileName:新建 Microsoft Word 文档.docx,fileExtension:.docx
fileName:研发分支管理.pptx,fileExtension:.pptx
fileName:研发标准化实践.png,fileExtension:.png
fileName:系统性能测试.xlsx,fileExtension:.xlsx