web判断文件的格式的时候,我们一般都是通过扩展名来判断,这个有点不太靠谱和安全。一般要判断是利用头文件来判断。下面是利用头文件来判断的代码:
class="根据头文件判断文件类型">package com.app.util; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class T { public static String bytesToHexString(byte[] src){ StringBuilder strBuilder = new StringBuilder(); if (src == null || src.length <= 0) { return null; } for (int i = 0; i < src.length; i++) { int v = src[i] & 0xFF; String strhs = Integer.toHexString(v); if (strhs.length() < 2) { strBuilder.append(0); } strBuilder.append(strhs); } return strBuilder.toString(); } /** * 根据文件流读取图片文件真实类型 * @param is * @return */ public static String getTypeByStream(FileInputStream is) { byte[] b = new byte[4]; try { is.read(b, 0, b.length); } catch (IOException e) { e.printStackTrace(); } String type = bytesToHexString(b).toUpperCase(); if (type.contains("FFD8FF")) { return "jpg"; } else if (type.contains("89504E47")) { return "png"; } else if (type.contains("47494638")) { return "gif"; } else if (type.contains("49492A00")) { return "tif"; } else if (type.contains("424D")) { return "bmp"; } return type; } public static void main(String args[]) { // String src = "D:/workspace//8129.jpg"; // String src = "D:/workspace//temp/1.gif"; String src = "D:/003-004-join.jpg"; FileInputStream is = null; try { is = new FileInputStream(src); } catch (FileNotFoundException e) { e.printStackTrace(); } // byte[] b = new byte[4]; // is.read(b, 0, b.length); // System.out.println(bytesToHexString(b)); String type = getTypeByStream(is); System.out.println(type); } }
?网上搜索了一些头文件的格式,但是强调一下,txt文件没有固定的头名,需要另外考虑,供参考: