public enum FileType {
JSP("3C25402070"),
EXE("4D5A9000030000000400"),
PHP("3131323331"),
BAT("406563686f206f66660d"),
// asp(""),
// asa(""),
// cer(""),
// cdx(""),
/**
* jpg.
*/
JPG("FFD8FF"),
/**
* PNG.
*/
PNG("89504E47"),
/**
* GIF.
*/
GIF("47494638"),
/**
* TIFF.
*/
TIFF("49492A00"),
/**
* RTF.
*/
RTF("7B5C727466"),
/**
* DOC
*/
DOC("D0CF11E0"),
/**
* XLS
*/
XLS("D0CF11E0"),
/**
* ACCESS
*/
MDB("5374616E64617264204A"),
/**
* Windows Bitmap.
*/
BMP("424D"),
/**
* CAD.
*/
DWG("41433130"),
/**
* Adobe Photoshop.
*/
PSD("38425053"),
/**
* XML.
*/
XML("3C3F786D6C"),
/**
* HTML.
*/
HTML("68746D6C3E"),
/**
* Adobe Acrobat.
*/
PDF("255044462D312E"),
/**
* ZIP Archive.
*/
ZIP("504B0304"),
/**
* RAR Archive.
*/
RAR("52617221"),
/**
* Wave.
*/
WAV("57415645"),
/**
* AVI.
*/
AVI("41564920");
private Stringvalue ="";
/**
* Constructor.
*
* @param value
*/
private FileType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
import com.jeedcp.modules.share.entity.FileType;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public final class FileTypeJudge {
/**
* 二进制转化为16进制
*/
private static String bytes2hex(byte[] bytes) {
StringBuilder hex =new StringBuilder();
for (int i =0; i < bytes.length; i++) {
String temp = Integer.toHexString(bytes[i] &0xFF);
if (temp.length() ==1) {
hex.append("0");
}
hex.append(temp.toLowerCase());
}
return hex.toString();
}
/**
* 读取文件头
*/
private static String getFileHeader(String filePath)throws IOException {
byte[] b =new byte[28];//这里需要注意的是,每个文件的magic word的长度都不相同,因此需要使用startwith
InputStream inputStream =null;
inputStream =new FileInputStream(filePath);
inputStream.read(b,0,28);
inputStream.close();
return bytes2hex(b);
}
/**
* 判断文件类型
*/
public static FileType getType(String filePath)throws IOException {
String fileHead =getFileHeader(filePath);
if (fileHead ==null || fileHead.length() ==0) {
return null;
}
fileHead = fileHead.toUpperCase();
FileType[] fileTypes = FileType.values();
for (FileType type : fileTypes) {
if (fileHead.startsWith(type.getValue())) {
return type;
}
}
return null;
}
public static void main(String[] args)throws Exception{
System.out.println(FileTypeJudge.getType("C:\\Users\\Admin\\Desktop\\picture\\888.png"));
}
}