java 文件头 文件类型 files_Android中Java根据文件头获取文件类型的方法

本文实例讲述了Android中Java根据文件头获取文件类型的方法。分享给大家供大家参考,具体如下:

前面讲过Android系统内部的MediaFile类来获取文件类型的办法,这个类主要是根据文件的扩展名来判断,其准确性不是很好。具体可查看Android系统使用MediaFile类判断音频文件类型。其实,获取文件类型最好的办法便是根据文件头信息来判断。下面贴出相关代码:

public class FileType {

public static final HashMap mFileTypes = new HashMap();

static {

//images

mFileTypes.put("FFD8FF", "jpg");

mFileTypes.put("89504E47", "png");

mFileTypes.put("47494638", "gif");

mFileTypes.put("49492A00", "tif");

mFileTypes.put("424D", "bmp");

//

mFileTypes.put("41433130", "dwg"); //CAD

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", "zip");

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("", "");

mFileTypes.put("", "");

}

public static String getFileType(String 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[3];

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);

}

return builder.toString();

}

public static void main(String[] args) throws Exception {

final String fileType = getFileType("D:/apache-tomcat-6.0.35.tar.gz");

System.out.println(fileType);

}

}

希望本文所述对大家Android程序设计有所帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值