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

Viewed 76123

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.org/2001/08/baseball/baseball-ont is http://www.daml.org/2001/08/baseball/baseball-ont.owl

When I do

    URI uri = new URI(address); 
    URL url = uri.toURL();
    String file = url.getFile();
    System.out.println(file);

I am not able to see the full file name with .owl extension, just /2001/08/baseball/baseball-ont how do I get the file extension as well. ``

8 Answers

Accepted answer is not useful for url contains '?' or '/' after extension. So, to remove that extra string, You can use getLastPathSegment() method. It gives you only name from uri and then you can get extension as follows:

String name = uri.getLastPathSegment();
//Here uri is your uri from which you want to get extension
String extension = name.substring(name.lastIndexOf("."));

above code gets extension with .(dot) if you want to remove the dot then you can code as follows:

String extension = name.substring(name.lastIndexOf(".") + 1);

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

I am doing it in this way.

You can check any file extension with more validation:

String stringUri = uri.toString();
String fileFormat = "png";

                    if (stringUri.contains(".") && fileFormat.equalsIgnoreCase(stringUri.substring(stringUri.lastIndexOf(".") + 1))) {

                        // do anything

                    } else {

                        // invalid file

                    }
Related