开发者

I need to open a file based on its mime type [duplicate]

This question already has answers here: How to get a file's Media Type (MIME type)? (27 answers) Closed 9 years ago.

I have the code to get the mime type. It seems to work. When I put mimeType in an if statement, I don't get the desired effect. Here are the snippets.

GET the mime type--

MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
String mimeType = mimeTypesMap.getContentType(file);

Now I want to only open a file if the mime type is text--

if (file.isFile()) {
try {
    if (mimeType == "text/plain") open开发者_开发百科File(file);
} catch (IOException e) {
    e.printStackTrace();
        System.err.print("    Cannot process file....\n");
}
}

This will not open a text file. Any ideas on why it will not work? openFile(file) works and is not the problem. file is a File Object. Thanks.


You're comparing the MIME type using ==, not String#equals() -- it's a String, yes? You probably have to do this:

if (mimeType.equals("text/plain")) openFile(file);

Or better still:

if ("text/plain".equals(mimeType)) openFile(file);

since that prevents a NPE from getting in your way.


Maybe the mime type is just text?

MIME types file search order:

The MimetypesFileTypeMap looks in various places in the user's system for MIME types file entries. When requests are made to search for MIME types in the MimetypesFileTypeMap, it searches MIME types files in the following order:

  1. Programmatically added entries to the MimetypesFileTypeMap instance.
  2. The file .mime.types in the user's home directory.
  3. The file /lib/mime.types.
  4. The file or resource named META-INF/mime.types.
  5. The file or resource named META-INF/mimetypes.default (usually found only in the activation.jar file).

Find this file and find out what mime type was specified for .txt files. Source: link

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜