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

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

    As other answers have explained, you don't really know the content type without inspecting the file. However, you can predict the file type from a URL.

    Java almost provides this functionality as part of the URL class. The method URL::getFile will intelligently grab the file portion of a URL:

    final URL url = new URL("http://www.example.com/a/b/c/stuff.zip?u=1");
    final String file = url.getFile(); // file = "/a/b/c/stuff.zip?u=1"
    

    We can use this to write our implementation:

    public static Optional<String> getFileExtension(final URL url) {
    
        Objects.requireNonNull(url, "url is null");
    
        final String file = url.getFile();
    
        if (file.contains(".")) {
    
            final String sub = file.substring(file.lastIndexOf('.') + 1);
    
            if (sub.length() == 0) {
                return Optional.empty();
            }
    
            if (sub.contains("?")) {
                return Optional.of(sub.substring(0, sub.indexOf('?')));
            }
    
            return Optional.of(sub);
        }
    
        return Optional.empty();
    }
    

    This implementation should handle edge-cases properly:

    assertEquals(
        Optional.of("zip"), 
        getFileExtension(new URL("http://www.example.com/stuff.zip")));
    
    assertEquals(
        Optional.of("zip"), 
        getFileExtension(new URL("http://www.example.com/stuff.zip")));
    
    assertEquals(
        Optional.of("zip"), 
        getFileExtension(new URL("http://www.example.com/a/b/c/stuff.zip")));
    
    assertEquals(
        Optional.empty(), 
        getFileExtension(new URL("http://www.example.com")));
    
    assertEquals(
        Optional.empty(), 
        getFileExtension(new URL("http://www.example.com/")));
    
    assertEquals(
        Optional.empty(), 
        getFileExtension(new URL("http://www.example.com/.")));
    
    0 讨论(0)
  • 2020-12-13 19:42

    At first, I want to make sure you know it's impossible to find out what kind of file a URI links too, since a link ending with .jpg might let you access a .exe file (this is especially true for URL's, due to symbolic links and .htaccess files), thus it isn't a rock solid solution to fetch the real extension from the URI if you want to limit allowed file types, if this is what you're going for of course. So, I assume you just want to know what extension a file has based on it's URI even though this isn't completely trustworthy;

    You can get the extension from any URI, URL or file path using the method bellow. You don't have to use any libraries or extensions, since this is basic Java functionality. This solution get's the position of the last . (period) sign in the URI string, and creates a sub-string starting at the position of the period sign, ending at the end of the URI string.

    String uri = "http://www.google.com/support/enterprise/static/gsa/docs/admin/70/gsa_doc_set/integrating_apps/images/google_logo.png";
    String extension = uri.substring(uri.lastIndexOf("."));
    

    This code sample will above will output the .png extension from the URI in the extension variable, note that a . (period) is included in the extension, if you want to gather the file extension without a prefixed period, increase the substring index by one, like this:

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

    One pro for using this method over regular expressions (a method other people use a lot) is that this is a lot less resource expensive and a lot less heavy to execute while giving the same result.

    Additionally, you might want to make sure the URL contains a period character, use the following code to achieve this:

    String uri = "http://www.google.com/support/enterprise/static/gsa/docs/admin/70/gsa_doc_set/integrating_apps/images/google_logo.png";
    if(uri.contains(".")) {
        String extension = uri.substring(url.lastIndexOf("."));
    }
    

    You might want to improve the functionally even further to create a more robust system. Two examples might be:

    • Validate the URI by checking it exists, or by making sure the syntax of the URI is valid, possibly using a regular expression.
    • Trim the extension to remove unwanted white spaces.

    I won't cover the solutions for these two features in here, because that isn't what was being asked in the first place.

    Hope this helps!

    0 讨论(0)
  • 2020-12-13 19:42

    This link might help for those who are still having problems: How I can get the mime type of a file having its Uri?

     public static String getMimeType(Context context, Uri uri) {
        String extension;
    
        //Check uri format to avoid null
        if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            //If scheme is a content
            final MimeTypeMap mime = MimeTypeMap.getSingleton();
            extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uri));
        } else {
            //If scheme is a File
            //This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file name with spaces and special characters.
            extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());
    
        }
    
        return extension;
    }
    
    0 讨论(0)
  • 2020-12-13 19:46

    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
    
                        }
    
    0 讨论(0)
  • 2020-12-13 19:49

    URLConnection.guessContentTypeFromName(url) would deliver the mime type as in the first answer. Maybe you simply wanted:

    String extension = url.getPath().replaceFirst("^.*/[^/]*(\\.[^\\./]*|)$", "$1");
    

    The regular expression consuming all upto the last slash, then upto a period and either returns an extension like ".owl" or "". (If not mistaken)

    0 讨论(0)
  • 2020-12-13 19:50

    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);
    
    0 讨论(0)
提交回复
热议问题