Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know whether a string path is Web URL or a File based

Tags:

java

file

url

I have a text field to acquire location information (String type) from User. It could be file directory based (e.g. C:\directory) or Web url (e.g. http://localhost:8008/resouces). The system will read some predetermined metadata file from the location.

Given the input string, how can I detect the nature of the path location whether it is a file based or Web URL effectively.

So far I have tried.

URL url = new URL(location); // will get MalformedURLException if it is a file based.
url.getProtocol().equalsIgnoreCase("http");

File file = new File(location); // will not hit exception if it is a url.
file.exist(); // return false if it is a url.

I am still struggling to find a best way to tackle both scenarios. :-(

Basically I would not prefer to explicitly check the path using the prefix such as http:// or https://

Is there an elegant and proper way of doing this?

like image 765
bLaXjack Avatar asked Aug 11 '14 07:08

bLaXjack


People also ask

Can a URL be a file path?

file is a registered URI scheme (for "Host-specific file names"). So yes, file URIs are URLs.

Is a URL and a path the same thing?

URL includes the protocol being used (http:// etc). Path doesn't or doesn't need at least. Also, URLs can percent-encode characters like spaces. Paths don't do that.

How do I find the URL of a path?

The getPath() function is a part of URL class. The function getPath() returns the Path name of a specified URL. Below programs illustrates the use of getPath() function: Example 1: Given a URL we will get the Path using the getPath() function.


1 Answers

If you're open to the use of a try/catch scenario being "elegant", here is a way that is more specific:

try {
    processURL(new URL(location));
}
catch (MalformedURLException ex){
    File file = new File(location);
    if (file.exists()) {
        processFile(file);
    }
    else {
        throw new PersonalException("Can't find the file");
    }
}

This way, you're getting the automatic URL syntax checking and, that failing, the check for file existence.

like image 143
John Chesshir Avatar answered Oct 12 '22 19:10

John Chesshir