javaandroidjava.nio.file

How to convert URL string into java.io.File in Android


I am overriding the android.webkit.WebViewClient method shouldInterceptRequest(WebView view, String url) in a custom class. In some cases, the url parameter points to an encrypted local file, in the form file:///path/to/file.extension. I need to convert the String url into a java.io.File to decrypt it.
How do I reliably convert the url parameter into a valid path to pass into new File(path)?


Solution

  • Use the following code:

    new File(new URL(url).toURI());
    

    but that would only work if URL is not hierarchical, which is your case. (For example you cannot do it if the URL points to a file in JAR file).