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

后端 未结 8 1820
一向
一向 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:52

    Another useful way which is not mentioned in accepted answer is, If you have a remote url, then you can get mimeType from URLConnection, Like

      URLConnection urlConnection = new URL("http://www.google.com").openConnection();
      String mimeType = urlConnection.getContentType(); 
    

    Now to get file extension from MimeType, I'll refer to this post

    0 讨论(0)
  • 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?

    0 讨论(0)
提交回复
热议问题