首页 > 其他分享 >识别一个文件的真实格式

识别一个文件的真实格式

时间:2022-09-23 08:45:20浏览次数:55  
标签:map file String 真实 File new put 格式 识别

识别一个文件的真实格式

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author Mxhlin
 * @Email [email protected]
 * @Date 2022/09/22/19:52
 * @Version
 * @Description  识别一个文件的真实格式
 */
public class Ex3 {


    public static void main(String[] args) {
        HashMap<String, String> map = new HashMap<>();
        map.put(".jpg","ffd8ffe0");
        map.put(".7z","377abcaf");
        map.put(".zip","504b34");
        map.put(".txt","aced05");
        System.out.println(map.containsKey(".7z"));

        System.out.println(getHeader(new File("D:\\IOTest\\112\\112.7z"), 4));

        String type = getType(new File("D:\\IOTest\\112\\112.7z"));
        System.out.println(type);
        // File file = new File("D:\\IOTest\\112");
        // File[] files = file.listFiles();
        // for (File file1 : files){
        //     String name = file1.getName();
        //     String hou = name.substring(name.lastIndexOf(".")).toLowerCase();
        //     System.out.printf("%s : %s : %s %n",name,hou,getHeader(file1,4));
        // }
    }

    public static String getType(File file){
        HashMap<String, String> map = new HashMap<>();
        map.put("ffd8ffe0",".jpg");
        map.put("377abcaf",".7z");
        map.put("504b34",".zip");
        map.put("aced05",".txt");
        String header = getHeader(file, 4);
        if (map.containsKey(header)){
            return map.get(header);
        }else {
            return "未知文件";
        }
    }


    public static String getHeader(File file,int n){
        String header = "";
        if (file.isFile()){
            try (FileInputStream fis = new FileInputStream(file)){
                byte[] bytes = new byte[n];
                fis.read(bytes);
                StringBuilder sb = new StringBuilder();
                for (byte byt : bytes){
                    sb.append(String.format("%x",byt));
                }
                header = sb.toString();
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return header;
    }
}

标签:map,file,String,真实,File,new,put,格式,识别
From: https://www.cnblogs.com/xhlin/p/16721471.html

相关文章