获取真正的文件扩展名-Java 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2091014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 19:23:05  来源:igfitidea点击:

Get real file extension -Java code

java

提问by Chan Pye

I would like to determine real file extension for security reason.

出于安全原因,我想确定真实的文件扩展名。

How can I do that?

我怎样才能做到这一点?

回答by Mark Elliot

Supposing you really mean to get the true content type of a file (ie it's MIME type) you should refer to this excellent answer.

假设您真的想获取文件的真实内容类型(即 MIME 类型),您应该参考这个优秀的答案

You can get the true content type of a file in Java using the following code:

您可以使用以下代码在 Java 中获取文件的真实内容类型:

File file = new File("filename.asgdsag");
InputStream is = new BufferedInputStream(new FileInputStream(file));
String mimeType = URLConnection.guessContentTypeFromStream(is);

回答by Kaleb Brasee

There are a number of waysthat you can do this, some more complicated (and more reliable) than others. The page I linked to discusses quite a few of these approaches.

很多方法可以做到这一点,有些方法比其他方法更复杂(也更可靠)。我链接到的页面讨论了很多这些方法。

回答by hgh

Not sure exactly what you mean, but however you do this it is only going to work for the specific set of file formats which are known to you

不确定您的意思,但是无论您这样做,它只适用于您已知的特定文件格式集

you could exclude executables (are you talking windows here?) - there's some file header information here http://support.microsoft.com/kb/65122- you could scan and block files which look like they have an exe header - is this getting close to what you mean when you say 'real file extension'?

你可以排除可执行文件(你在这里说的是 windows 吗?) - 这里有一些文件头信息http://support.microsoft.com/kb/65122- 你可以扫描和阻止看起来像他们有一个 exe 头的文件 - 这是当您说“真实文件扩展名”时,接近您的意思吗?