您的位置:首页 > 编程语言 > Java开发

Java通过文件头获取文件类型

2017-11-01 17:20 411 查看
public class FileCheckTypeUtil {
private static Logger logger = LogManager.getLogger(FileCheckTypeUtil.class);
static Map<String,String> map = null;
static {
map =new HashMap<>();
map.put("FFD8FF","jpg");
map.put("89504E","png");
map.put("474946","gif");
map.put("524946","webp");
map.put("000001","ico");
map.put("424D36","bmp");
map.put("00000A","tga");
map.put("49492A","tif");
}

private  static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}

private  static  String checkType(String code){
return map.get(code);
}

/**
* 获得图片后缀
* @param path
* @return
*/
public static String getType(String path){
String type ="";
FileInputStream fileInputStream =null;
try {
fileInputStream = new FileInputStream(path);
byte[] b = new byte[3];
fileInputStream.read(b, 0, b.length);
String code = bytesToHexString(b);
code = code.toUpperCase();
type = checkType(code);

}catch (Exception e){
logger.error("获取文件格式异常");
}finally {
if(fileInputStream!=null){
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return type;
}

public static void main(String[] args) throws IOException {
String path = "E:\\redis64-2.8.9.zip";
System.out.println(getType(path));
}
}
文件类型需要提前穷举
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 文件