具深圳网站建设公司鲍余网络的技术工程师介绍:java判断检验各种文件类型,通过读取文件头(前4位),可判断gz等格式,代码如下:
-
import java.io.FileInputStream;
-
import java.io.IOException;
-
import java.util.HashMap;
-
-
-
-
-
-
-
-
public class GetTypeByHead {
-
-
public static final HashMap<String, String> mFileTypes = new HashMap<String, String>();
-
static {
-
-
mFileTypes.put("FFD8FF", "jpg");
-
mFileTypes.put("89504E47", "png");
-
mFileTypes.put("47494638", "gif");
-
mFileTypes.put("49492A00", "tif");
-
mFileTypes.put("424D", "bmp");
-
-
mFileTypes.put("41433130", "dwg");
-
mFileTypes.put("38425053", "psd");
-
mFileTypes.put("7B5C727466", "rtf");
-
mFileTypes.put("3C3F786D6C", "xml");
-
mFileTypes.put("68746D6C3E", "html");
-
mFileTypes.put("44656C69766572792D646174653A", "eml");
-
mFileTypes.put("D0CF11E0", "doc");
-
mFileTypes.put("5374616E64617264204A", "mdb");
-
mFileTypes.put("252150532D41646F6265", "ps");
-
mFileTypes.put("255044462D312E", "pdf");
-
mFileTypes.put("504B0304", "docx");
-
mFileTypes.put("52617221", "rar");
-
mFileTypes.put("57415645", "wav");
-
mFileTypes.put("41564920", "avi");
-
mFileTypes.put("2E524D46", "rm");
-
mFileTypes.put("000001BA", "mpg");
-
mFileTypes.put("000001B3", "mpg");
-
mFileTypes.put("6D6F6F76", "mov");
-
mFileTypes.put("3026B2758E66CF11", "asf");
-
mFileTypes.put("4D546864", "mid");
-
mFileTypes.put("1F8B08", "gz");
-
mFileTypes.put("4D5A9000", "exe/dll");
-
mFileTypes.put("75736167", "txt");
-
}
-
-
-
-
-
-
-
-
-
public static String getFileType(String filePath) {
-
System.out.println(getFileHeader(filePath));
-
System.out.println(mFileTypes.get(getFileHeader(filePath)));
-
return mFileTypes.get(getFileHeader(filePath));
-
}
-
-
-
-
-
-
-
-
-
public static String getFileHeader(String filePath) {
-
FileInputStream is = null;
-
String value = null;
-
try {
-
is = new FileInputStream(filePath);
-
byte[] b = new byte[4];
-
-
-
-
-
-
is.read(b, 0, b.length);
-
value = bytesToHexString(b);
-
} catch (Exception e) {
-
} finally {
-
if (null != is) {
-
try {
-
is.close();
-
} catch (IOException e) {
-
}
-
}
-
}
-
return value;
-
}
-
-
-
-
-
-
-
-
-
private static String bytesToHexString(byte[] src) {
-
StringBuilder builder = new StringBuilder();
-
if (src == null || src.length <= 0) {
-
return null;
-
}
-
String hv;
-
for (int i = 0; i < src.length; i++) {
-
-
hv = Integer.toHexString(src[i] & 0xFF).toUpperCase();
-
if (hv.length() < 2) {
-
builder.append(0);
-
}
-
builder.append(hv);
-
}
-
System.out.println(builder.toString());
-
return builder.toString();
-
}
-
-
public static void main(String[] args) throws Exception {
-
final String fileType = getFileType("D:\\Ry4S_JAVA.dll");
-
System.out.println(fileType);
-
}
-
}
推荐阅读:JS代码属性详解:window.location
深圳网站建设专家:鲍余网络
8年专注:网站设计、网站建设、网站开发、营销型网站建设、营销型网站设计、APP开发、软件开发、微信开发、公众号开发、互动营销、响应式网站建设开发、响应式网站、互联网形象设计、空间租用、域名注册、虚拟主机、服务器托管、网站维护等服务。
鲍余案例:稳健医疗、格力地产、珠海气象局、大昌行集团等知名企业
咨询热线:0755-3693 8799
咨询QQ:8554 3483
联系人:鲍先生:
电话:185 7667 8080
微信:185 7667 8080
地址:深圳市龙华新区民治大道沙元埔大厦12楼1205-1228室(民治地铁站D出口对面)
网址:www.zgbywl.com