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?
file is a registered URI scheme (for "Host-specific file names"). So yes, file URIs are URLs.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With