Converting Java file:// URL to File(…) path, platform independent, including UNC paths

前端 未结 5 1004
再見小時候
再見小時候 2020-12-05 17:49

I am developing a platform independent application. I am receiving a file URL*. On windows these are:

  • file:///Z:/folder%20to%20file/file.txt

5条回答
  •  悲&欢浪女
    2020-12-05 18:12

    Building on @SotiriosDelimanolis's comment, here is a method to deal with URLs (such as file:...) and non-URLs (such as C:...), using Spring's FileSystemResource:

    public FileSystemResource get(String file) {
        try {
            // First try to resolve as URL (file:...)
            Path path = Paths.get(new URL(file).toURI());
            FileSystemResource resource = new FileSystemResource(path.toFile());
            return resource;
        } catch (URISyntaxException | MalformedURLException e) {
            // If given file string isn't an URL, fall back to using a normal file 
            return new FileSystemResource(file);
        }
    }
    

提交回复
热议问题