Check the file header, i.e. the first few bytes of the file. The same principle applies to common MIME Type parsing. Because your needs are very simple, I do not recommend third-party packages for MIME type judgment here. The first few bytes of the RTF definition type are searched and queried (hexadecimal): 7B 5C 72 74 66 So you only need to read the first five bytes of the file and then convert it into hexadecimal form. string, and then compare it with "7b5c727466" to determine whether it is an RTF type.
FileInputStream fis = new FileInputStream(file);
byte[] bytes = new byte[5];
fis.read(bytes, 0, bytes.length);
fis.close();
StringBuffer header=new StringBuffer();
for (byte b : bytes) {
String hex=Integer.toHexString(b);
if(hex.length()<2){// 两位以下补〇
header.append('0');
}
header.append(hex);
}
boolean isRTF="7b5c727466".contentEquals(header);
Check the file header, i.e. the first few bytes of the file. The same principle applies to common MIME Type parsing. Because your needs are very simple, I do not recommend third-party packages for MIME type judgment here.
The first few bytes of the RTF definition type are searched and queried (hexadecimal): 7B 5C 72 74 66
So you only need to read the first five bytes of the file and then convert it into hexadecimal form. string, and then compare it with "7b5c727466" to determine whether it is an RTF type.