在java中获取文件的mime类型

ecfdbz9o  于 2021-06-20  发布在  Mysql
关注(0)|答案(24)|浏览(689)

我只是想知道大多数人是如何从java文件中获取mime类型的?到目前为止,我已经尝试了两种方法: JMimeMagic & Mime-Util .
第一个给了我内存异常,第二个没有正确关闭它的流。我只是想知道是否有其他人有一个方法/库,他们使用和工作正常?

brqmpdu1

brqmpdu116#

在Java7中,您现在只需使用 Files.probeContentType(path) .

4xy9mtcn

4xy9mtcn17#

apache tika在tika core中提供了一种基于流前缀中的魔术标记的mime类型检测。 tika-core 不获取其他依赖项,这使得它与当前未维护的mime类型检测实用程序一样轻量级。
简单代码示例(Java7),使用变量 theInputStream 以及 theFileName ```
try (InputStream is = theInputStream;
BufferedInputStream bis = new BufferedInputStream(is);) {
AutoDetectParser parser = new AutoDetectParser();
Detector detector = parser.getDetector();
Metadata md = new Metadata();
md.add(Metadata.RESOURCE_NAME_KEY, theFileName);
MediaType mediaType = detector.detect(bis, md);
return mediaType.toString();
}

请注意 `MediaType.detect(...)` 不能直接使用(tika-1120)。更多提示请参见https://tika.apache.org/1.24/detection.html.
btqmn9zl

btqmn9zl18#

对于apache tika,您只需要三行代码:

File file = new File("/path/to/file");
Tika tika = new Tika();
System.out.println(tika.detect(file));

如果您有groovy控制台,只需粘贴并运行以下代码即可:

@Grab('org.apache.tika:tika-core:1.14')
import org.apache.tika.Tika;

def tika = new Tika()
def file = new File("/path/to/file")
println tika.detect(file)

记住,它的api是丰富的,它可以解析“任何东西”。从tika core 1.14开始,您有:

String  detect(byte[] prefix)
String  detect(byte[] prefix, String name)
String  detect(File file)
String  detect(InputStream stream)
String  detect(InputStream stream, Metadata metadata)
String  detect(InputStream stream, String name)
String  detect(Path path)
String  detect(String name)
String  detect(URL url)

有关更多信息,请参阅apidocs。

nszi6y05

nszi6y0519#

我找不到要检查的东西 video/mp4 所以我做了自己的解决方案。我碰巧注意到维基百科错了 00 00 00 18 66 74 79 70 69 73 6F 6D 文件签名不正确。第四字节( 18 )以及所有 70 (排除在外)在其他情况下发生了相当多的变化 mp4 文件夹。
此代码本质上是 URLConnection.guessContentTypeFromStream 代码,但适合 video/mp4 .

BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(content));
String mimeType = URLConnection.guessContentTypeFromStream(bis);

// Goes full barbaric and processes the bytes manually
if (mimeType == null){
    // These ints converted in hex ar:
    // 00 00 00 18 66 74 79 70 69 73 6F 6D
    // which are the file signature (magic bytes) for .mp4 files
    // from https://www.wikiwand.com/en/List_of_file_signatures
    // just ctrl+f "mp4"
    int[] mp4_sig = {0, 0, 0, 24, 102, 116, 121, 112};

    bis.reset();
    bis.mark(16);
    int[] firstBytes = new int[8];
    for (int i = 0; i < 8; i++) {
        firstBytes[i] = bis.read();
    }
    // This byte doesn't matter for the file signature and changes
    mp4_sig[3] = content[3];

    bis.reset();
    if (Arrays.equals(firstBytes, mp4_sig)){
        mimeType = "video/mp4";
    }
}

成功测试了10种不同的 .mp4 文件夹。
编辑:这里有一个有用的链接(如果它仍然在线的话),你可以在这里找到许多类型的样本。我不拥有这些视频,也不知道谁拥有,但它们对测试上述代码很有用。

monwx1rj

monwx1rj20#

我只是想知道大多数人是如何从java文件中获取mime类型的?
我已经发布了我的simplemagicjava包,它允许从文件和字节数组中确定内容类型(mime类型)。它被设计用来读取和运行unix文件(1)命令魔术文件,这些文件是大多数unix操作系统配置的一部分。
我试过apache tika,但它有很多依赖项, URLConnection 不使用文件的字节 MimetypesFileTypeMap 也只看文件名。
使用simplemagic,您可以执行以下操作:

// create a magic utility using the internal magic file
ContentInfoUtil util = new ContentInfoUtil();
// if you want to use a different config file(s), you can load them by hand:
// ContentInfoUtil util = new ContentInfoUtil("/etc/magic");
...
ContentInfo info = util.findMatch("/tmp/upload.tmp");
// or
ContentInfo info = util.findMatch(inputStream);
// or
ContentInfo info = util.findMatch(contentByteArray);

// null if no match
if (info != null) {
   String mimeType = info.getMimeType();
}
rqcrx0a6

rqcrx0a621#

只需一行即可完成:mimetypesfiletypemap().getcontenttype(新文件(“filename.ext”))。查看完整的测试代码(java 7):

import java.io.File;
import javax.activation.MimetypesFileTypeMap;
public class MimeTest {
    public static void main(String a[]){
         System.out.println(new MimetypesFileTypeMap().getContentType(
           new File("/path/filename.txt")));
    }
}

此代码生成以下输出:text/plain

h79rfbju

h79rfbju22#

这是我找到的最简单的方法:

byte[] byteArray = ...
InputStream is = new BufferedInputStream(new ByteArrayInputStream(byteArray));
String mimeType = URLConnection.guessContentTypeFromStream(is);
kuhbmx9i

kuhbmx9i23#

我是用下面的代码做的。

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MimeFileType {

    public static void main(String args[]){

        try{
            URL url = new URL ("https://www.url.com.pdf");

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            InputStream content = (InputStream)connection.getInputStream();
            connection.getHeaderField("Content-Type");

            System.out.println("Content-Type "+ connection.getHeaderField("Content-Type"));

            BufferedReader in = new BufferedReader (new InputStreamReader(content));

        }catch (Exception e){

        }
    }
}
8cdiaqws

8cdiaqws24#

File file = new File(PropertiesReader.FILE_PATH);
MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
String mimeType = fileTypeMap.getContentType(file);
URLConnection uconnection = file.toURL().openConnection();
mimeType = uconnection.getContentType();

相关问题