Android 根據(jù)文件頭獲取準確file類型

最近在項目中需要判斷從網(wǎng)絡上下載下來的文件類型,方法有 :
1、根據(jù)header中content-type字段類型來指定下載的文件類型,缺點:如果是未知服務器無法保證字段準確性;
2、根據(jù)文件后綴名稱,缺點:還不夠嚴格(有可能手動修改后綴名稱),
3、使用根據(jù)讀取頭文件部分內(nèi)容與標準格式文件對比,即可準確判斷文件類型,這里可以讀取3個字節(jié),或者10個字節(jié),缺點:文件類型可能不全

根據(jù)文件頭獲取準確file類型的代碼具體如下:

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;
import com.huawei.hms.framework.common.IoUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;

public class FileTypeUtils {

protected static final String MIMETYPES_PROPERTIES = "FileTypes.properties";
protected static Properties mFileTypes;
private static FileTypeUtils fileTypeUtils;

private FileTypeUtils(Context context) {
    try {
        mFileTypes = new Properties();
        mFileTypes.load(context.getAssets().open(MIMETYPES_PROPERTIES));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static FileTypeUtils getInstance(Context appContext) {
    if (fileTypeUtils == null) {
        fileTypeUtils = new FileTypeUtils(appContext);
    }
    return fileTypeUtils;
}

public String getFileType(File file) {
    if (file == null) {
        return null;
    }
    if (!file.exists() || file.length() < 11) {
        return null;
    }
    String header = get10ByteHeader(file);
    String fileSuffix = mFileTypes.getProperty(header);
    /*
     * 優(yōu)化處理:在不同的設備上同樣類型的文件,文件頭前面內(nèi)容未必一致,可能只有前幾個一致,后面就不同了
     * (例如:jpg類型文件,在不同手機上,lennovo k900前10個是一致的,但是MI3只有前5個字符一致,后面是不一樣的,所有一些情況進行特殊處理)當整個頭文件失敗后,
     * 在進行前5個字符截取對比處理,優(yōu)化具體如下:
     */
    if (TextUtils.isEmpty(fileSuffix)) {

        Iterator keyList = mFileTypes.keySet().iterator();
        //并不是所有的文件格式前10 byte(jpg)都一致,前五個byte一致即可
        String key, keySearchPrefix = header.substring(0, 5);
        while (keyList.hasNext()) {
            key = (String) keyList.next();
            if (key.contains(keySearchPrefix)) {
                fileSuffix = mFileTypes.getProperty(key);
                break;
            }
        }
    }

    //前5個字符截取對比處理沒有找到,則進行特殊處理
    if (TextUtils.isEmpty(fileSuffix)) {
        header = get3ByteHeader(file);
        fileSuffix = mFileTypes.getProperty(header);
    }

    return fileSuffix;
}

public String getFileType(byte[] bytes) {
    if (bytes == null || bytes.length < 11) {
        return null;
    }

    String header = bytesToHexString(subarray(bytes, 0, 10));
    String fileSuffix = mFileTypes.getProperty(header);
    /*
     * 優(yōu)化處理:在不同的設備上同樣類型的文件,文件頭前面內(nèi)容未必一致,可能只有前幾個一致,后面就不同了
     * (例如:jpg類型文件,在不同手機上,lennovo k900前10個是一致的,但是MI3只有前5個字符一致,后面是不一樣的,所有一些情況進行特殊處理)當整個頭文件失敗后,
     * 在進行前5個字符截取對比處理,優(yōu)化具體如下:
     */
    if (TextUtils.isEmpty(fileSuffix)) {
        Iterator keyList = mFileTypes.keySet().iterator();
        //并不是所有的文件格式前10 byte(jpg)都一致,前五個byte一致即可
        String key, keySearchPrefix = header.substring(0, 5);
        while (keyList.hasNext()) {
            key = (String) keyList.next();
            if (key.contains(keySearchPrefix)) {
                fileSuffix = mFileTypes.getProperty(key);
                break;
            }
        }
    }

    //前5個字符截取對比處理沒有找到,則進行特殊處理
    if (TextUtils.isEmpty(fileSuffix)) {
        header = bytesToHexString(subarray(bytes, 0, 3));
        fileSuffix = mFileTypes.getProperty(header);
    }

    return fileSuffix;

}

public byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {
    if (array == null) {
        return null;
    }
    if (startIndexInclusive < 0) {
        startIndexInclusive = 0;
    }
    if (endIndexExclusive > array.length) {
        endIndexExclusive = array.length;
    }
    final int newSize = endIndexExclusive - startIndexInclusive;
    if (newSize <= 0) {
        return new byte[0];
    }

    final byte[] subarray = new byte[newSize];
    System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
    return subarray;
}

@SuppressWarnings("deprecation")
private String get10ByteHeader(File file) {
    InputStream input = null;
    String value = null;
    try {
        input = new FileInputStream(file);
        byte[] b = new byte[10];
        input.read(b, 0, b.length);
        value = bytesToHexString(b);
    } catch (Exception e) {
    } finally {
        IoUtils.closeSecure(input);
    }
    return value;
}

@SuppressWarnings("deprecation")
private String get3ByteHeader(File file) {
    InputStream input = null;
    String value = null;
    try {
        input = new FileInputStream(file);
        byte[] b = new byte[3];
        input.read(b, 0, b.length);
        value = bytesToHexString(b);
    } catch (Exception e) {
    } finally {
        IoUtils.closeSecure(input);
    }
    return value;
}

private 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();
}

}

在assets資源目錄下新建properties文件,命名為:“FileTypes.properties”

# 常見文件頭信息(該文件中的文件頭需要為大寫)

#JPEG (jpg)
FFD8FFE000104A464946=jpg
#PNG (png)
89504E470D0A1A0A0000=png
#GIF (gif)
47494638396126026F01=gif
#TIFF (tif)
49492A00227105008037=tif
#16色位圖(bmp)
424D228C010000000000=bmp
#24位位圖(bmp)
424D8240090000000000=bmp
#256色位圖(bmp)
424D8E1B030000000000=bmp
#CAD (dwg)
41433130313500000000=dwg
#HTML (html)
3C21444F435459504520=html
#HTM (htm)
3C21646F637479706520=htm
#css
48544D4C207B0D0A0942=css
#js
696B2E71623D696B2E71=js
#Rich Text Format (rtf)
7B5C727466315C616E73=rtf
#Photoshop (psd)
38425053000100000000=psd
#Email [Outlook Express 6] (eml)
46726F6D3A203D3F6762=eml
#MS Excel 注意:word、msi 和 excel的文件頭一樣
D0CF11E0A1B11AE10000=doc
#Visio 繪圖
D0CF11E0A1B11AE10000=vsd
#MS Access (mdb)
5374616E64617264204A=mdb
252150532D41646F6265=ps
#Adobe Acrobat (pdf)
255044462D312E350D0A=pdf
#rmvb/rm相同
2E524D46000000120001=rmvb
#flv與f4v相同
464C5601050000000900=flv
00000020667479706D70=mp4
49443303000000002176=mp3
000001BA210001000180=mpg
#wmv與asf相同
3026B2758E66CF11A6D9=wmv
#Wave (wav)
52494646E27807005741=wav
52494646D07D60074156=avi
#MIDI (mid)
4D546864000000060001=mid
504B0304140000000800=zip
526172211A0700CF9073=rar
235468697320636F6E66=ini
504B03040A0000000000=jar
#可執(zhí)行文件
4D5A9000030000000400=exe
#jsp文件
3C25402070616765206C=jsp
#MF文件
4D616E69666573742D56=mf
#xml文件
3C3F786D6C2076657273=xml
#sql文件
494E5345525420494E54=sql
#java文件
7061636B616765207765=java
#bat文件
406563686F206F66660D=bat
#gz文件
1F8B0800000000000000=gz
#bat文件
6C6F67346A2E726F6F74=properties
CAFEBABE0000002E0041=class
49545346030000006000=chm
04000000010000001300=mxp
#docx文件
504B0304140006000800=docx
#WPS文字wps、表格et、演示dps都是一樣的
D0CF11E0A1B11AE10000=wps
6431303A637265617465=torrent

#Quicktime (mov)
6D6F6F76=mov
#WordPerfect (wpd)
FF575043=wpd
#Outlook Express (dbx)
CFAD12FEC5FD746F=dbx
#Outlook (pst)
2142444E=pst
#Quicken (qdf)
AC9EBD8F=qdf
#Windows Password (pwl)
E3828596=pwl
#Real Audio (ram)
2E7261FD=ram

#五字節(jié)文件頭對應關系

255044=PDF
526563=EML
D0CF11=PPT
4D5AEE=COM
E93B03=COM
4D5A90=EXE
424D3E=BMP
49492A=TIF
384250=PSD
C5D0D3=EPS
0A0501=PCS
89504E=PNG
060500=RAW
000002=TGA
60EA27=ARJ
526172=RAR
504B03=ZIP
495363=CAB
1F9D8C=Z
524946=WAV
435753=SWF
3026B2=WMV
3026B2=WMA
2E524D=RM
00000F=MOV
000077=MOV
000001=MPA
FFFB50=MP3
234558=m3u
3C2144=HTM
FFFE3C=XSL
3C3F78=XML
3C3F78=MSC
4C0000=LNK
495453=CHM
805343=scm
D0CF11=XLS
31BE00=WRI
00FFFF=MDF
4D4544=MDS
5B436C=CCD
00FFFF=IMG
FFFFFF=SUB
17A150=PCB
2A5052=ECO
526563=PPC
000100=DDB
42494C=LDB
2A7665=SCH
2A2420=LIB
434841=FNT
7B5C72=RTF
7B5072=GTD
234445=PRG
000007=PJT
202020=BAS
000002=TAG
4D5A90=dll
4D5A90=OCX
4D5A50=DPL
3F5F03=HLP
4D5A90=OLB
4D5A90=IMM
4D5A90=IME
3F5F03=LHP
C22020=NLS
5B5769=CPX
4D5A16=DRV
5B4144=PBK
24536F=PLL
4E4553=NES
87F53E=GBC
00FFFF=SMD
584245=XBE
005001=XMV
000100=TTF
484802=PDG
000100=tst
414331=dwg
D0CF11=max

#特殊情況下的文件頭

#images
FFD8FF=jpg
89504E47=png
47494638=gif
49492A00=tif
424D=bmp
#CAD
41433130=dwg
38425053=psd
7B5C727466=rtf
3C3F786D6C=xml
68746D6C3E=html
44656C69766572792D646174653A=eml
D0CF11E0=doc
5374616E64617264204A=mdb
252150532D41646F6265=ps
255044462D312E=pdf
504B0304=zip
52617221=rar
57415645=wav
41564920=avi
2E524D46=rm
000001BA=mpg
000001B3=mpg
6D6F6F76=mov
3026B2758E66CF11=asf
4D546864=mid
1F8B08=gz
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容