How to determine the file extension of a file from a uri

后端 未结 8 1855
一向
一向 2020-12-13 19:06

Assuming I am given a URI, and I want to find the file extension of the file that is returned, what do I have to do in Java.

For example the file at http://www.daml.

8条回答
  •  星月不相逢
    2020-12-13 19:56

    There are two answers to this.

    If a URI does not have a "file extension", then there is no way that you can infer one by looking at it textually, or by converting it to a File. In general, neither the URI or the File needs to have an extension at all. Extensions are just a file naming convention.

    What you are really after is the media type / MIMEtype / content type of the file. You may be able to determine the media type by doing something like this:

    URLConnection conn = url.connect();
    String type = conn.getContentType();
    

    However the getContentType() method will return null if the server did not set a content type in the response. (Or it could give you the wrong content type, or a non-specific content type.) At that point, you would need to resort to content type "guessing", and I don't know if that would give you a specific enough type in this case.

    But if you "know" that the file should be OWL, why don't you just give it a ".owl" extension anyway?

提交回复
热议问题