如何从字节数组中提取文件扩展名
2022-09-01 16:42:47
我在数据库中有字节数组。
如何从java中的字节数组中提取文件扩展名(mime /type)?
我在数据库中有字节数组。
如何从java中的字节数组中提取文件扩展名(mime /type)?
原来,类中有一个不错的方法,请参考以下答案:在Java中获取文件的哑剧类型JDK
URLConnection
如果需要从字节数组而不是文件中提取文件扩展名,则应直接使用(类专门从字节数组读取字节)而不是(类专门从文件中读取字节),如以下示例所示:java.io.ByteArrayInputStream
java.io.FileInputStream
byte[] content = ;
InputStream is = new ByteArrayInputStream(content);
String mimeType = URLConnection.guessContentTypeFromStream(is);
//...close stream
希望这有帮助...
如果这是为了存储上传的文件:
如果您没有原始文件,并且只有字节,那么您有几个很好的解决方案。
如果您能够使用库,请查看使用 mime-util 检查字节:
http://technopaper.blogspot.com/2009/03/identifying-mime-using-mime-util.html
如果你必须构建自己的字节检测器,这里有许多最流行的起始字节:
"BC" => bitcode,
"BM" => bitmap,
"BZ" => bzip,
"MZ" => exe,
"SIMPLE"=> fits,
"GIF8" => gif,
"GKSM" => gks,
[0x01,0xDA].pack('c*') => iris_rgb,
[0xF1,0x00,0x40,0xBB].pack('c*') => itc,
[0xFF,0xD8].pack('c*') => jpeg,
"IIN1" => niff,
"MThd" => midi,
"%PDF" => pdf,
"VIEW" => pm,
[0x89].pack('c*') + "PNG" => png,
"%!" => postscript,
"Y" + [0xA6].pack('c*') + "j" + [0x95].pack('c*') => sun_rasterfile,
"MM*" + [0x00].pack('c*') => tiff,
"II*" + [0x00].pack('c*') => tiff,
"gimp xcf" => gimp_xcf,
"#FIG" => xfig,
"/* XPM */" => xpm,
[0x23,0x21].pack('c*') => shebang,
[0x1F,0x9D].pack('c*') => compress,
[0x1F,0x8B].pack('c*') => gzip,
"PK" + [0x03,0x04].pack('c*') => pkzip,
"MZ" => dos_os2_windows_executable,
".ELF" => unix_elf,
[0x99,0x00].pack('c*') => pgp_public_ring,
[0x95,0x01].pack('c*') => pgp_security_ring,
[0x95,0x00].pack('c*') => pgp_security_ring,
[0xA6,0x00].pack('c*') => pgp_encrypted_data,
[0xD0,0xCF,0x11,0xE0].pack('c*') => docfile