package common.util; import java.io.File; import org.apache.commons.io.FileUtils; import org.apache.tika.Tika; import org.apache.tika.mime.MimeTypes; public class ExtUtil { public static String getExt(byte[] bts) { try { Tika tika = new Tika(); String fileType = tika.detect(bts); return MimeTypes.getDefaultMimeTypes().forName(fileType).getExtension(); } catch (Exception e) { e.printStackTrace(); } return ""; } public static void main(String[] args) throws Exception { String path = "C:\Users\Administrator\Desktop\format_img\a.xls"; File f = new File(path); byte[] ext = FileUtils.readFileToByteArray(f); System.out.println(getExt(ext)); } }
所需jar包maven坐标
<!-- https://mvnrepository.com/artifact/org.apache.tika/tika-core --> <dependency> <groupId>org.apache.tika</groupId> <artifactId>tika-core</artifactId> <version>1.26</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency>