package com.matrix.core.tools; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.apache.commons.io.IOUtils; /** * 文件类型判断工具 * * @author JIANGYOUYAO * @email 935090232@qq.com * @date 2017年12月12日 */ public class FileTypeUtil { /** * 通过文件头的特定字符 校验文件是否为列表中的一种 * * @author JIANGYOUYAO * @email 935090232@qq.com * @date 2017年12月20日 * @param file * @param fileTypes * @return * @throws IOException */ public static boolean checkFileType(File file, List fileTypes) throws IOException { FileInputStream stream = new FileInputStream(file); byte[] data = new byte[28]; IOUtils.readFully(stream, data); String fileHead = bytes2hex(data).toUpperCase(); for (FileType fileType : fileTypes) { if (fileHead.startsWith(fileType.getValue())) { return true; } } return false; } public static boolean checkFileType(InputStream stream , List fileTypes) throws IOException { byte[] data = new byte[28]; IOUtils.readFully(stream, data); String fileHead = bytes2hex(data).toUpperCase(); for (FileType fileType : fileTypes) { if (fileHead.startsWith(fileType.getValue())) { return true; } } return false; } private static String bytes2hex(byte[] b) { StringBuffer hexStr = new StringBuffer(); for (int i = 0; i < b.length; i++) { String hex = Integer.toHexString(b[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } hexStr.append(hex); } return hexStr.toString(); } /** * 获取文件扩展名称 * * @author JIANGYOUYAO * @email 935090232@qq.com * @date 2017年12月20日 * @param file * @return */ public static String getFileExtName(File file) { String fileName = file.getName(); String prefix = fileName.substring(fileName.lastIndexOf(".") ); return prefix; } }