如何知道字符串路径是Web URL还是基于文件

bLa*_*ack 7 java url file

我有一个文本字段来从用户获取位置信息(字符串类型).它可以是基于文件目录(例如C:\directory)或Web URL(例如http://localhost:8008/resouces).系统将从该位置读取一些预定的元数据文件.

给定输入字符串,我如何有效地检测路径位置的性质,无论是基于文件还是Web URL.

到目前为止我已经尝试过.

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.
Run Code Online (Sandbox Code Playgroud)

我仍然在努力寻找解决这两种情况的最佳方法.:-(

基本上我不希望使用诸如http://或的前缀显式检查路径https://

这样做有一种优雅而恰当的方式吗?

icz*_*cza 5

您可以检查是否locationhttp://或开头https://:

String s = location.trim().toLowerCase();
boolean isWeb = s.startsWith("http://") || s.startsWith("https://");
Run Code Online (Sandbox Code Playgroud)

或者您可以使用URI类代替URL,而URI不是MalformedURLExceptionURL类一样抛出:

URI u = new URI(location);
boolean isWeb = "http".equalsIgnoreCase(u.getScheme())
    || "https".equalsIgnoreCase(u.getScheme())
Run Code Online (Sandbox Code Playgroud)

虽然new URI()也可能抛出URISyntaxException,如果你在的地方使用反斜线例如.最好的方法是使用前缀检查(我的第一个建议)或创建一个URL和捕获MalformedURLException,如果抛出你会知道它不能是一个有效的网址.