您的位置:首页 > 其它

以16进制的方式判断文件上传的类型

2018-01-04 14:12 489 查看
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileTypeUtil {

private FileTypeUtil() {
}

/**
* 把文件头转换成16进制
* @param src
* @return
*/
private static String bytesToHexString(byte[] src) {
StringBuilder sb = new StringBuilder();
if (src == null || src.length < 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int h = src[i] & 0xFF;
String hv = Integer.toHexString(h);
if (hv.length() < 2) {
sb.append(0);
}
sb.append(hv);
}
return sb.toString().toUpperCase();
}

private static String getFileContent(String filePath) {
byte[] bytes = new byte[28];
File file = new File(filePath);
if(!file.exists()){
return null;
}
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(file);
fileInputStream.read(bytes, 0, 28);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return bytesToHexString(bytes);
}

public static FileType getFileType(String filePath) {
if (filePath == null || filePath == "") {
return null;
}
String fileContent = getFileContent(filePath);
if (fileContent == null || fileContent == "") {
return null;
}
FileType[] fileTypes = FileType.values();
for (FileType fileType : fileTypes) {
if (fileContent.startsWith(fileType.getValue())) {
return fileType;
}
}
return null;
}

public static void main(String[] args) {
String s = getFileType("E:\\QP\\7a76a296b072ebe17507bd31709e9dc4.png").name().toLowerCase();
if (s != null && s != "") {
System.out.println(s);
}
}

public static enum FileType {
/**
* JEPG.
*/
JPEG("FFD8FF"),

/**
* PNG.
*/
PNG("89504E47"),

/**
* GIF.
*/
GIF("47494638"),

/**
* TIFF.
*/
TIFF("49492A00"),

/**
* Windows Bitmap.
*/
BMP("424D"),

/**
* CAD.
*/
DWG("41433130"),

/**
* Adobe Photoshop.
*/
PSD("38425053"),
/**
* MS Word/Excel.
*/
XLS_DOC("D0CF11E0"),

XLSX_DOCX("504B0304"),

/**
* Rich Text Format.
*/
RTF("7B5C727466");

private String value;

private FileType(String value) {
this.value = value;
}

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: