原文链接: https://www.iteye.com/blog/jsczxy2-1683516
//绝对路径
String absolutePath = "http://www.aaa.com/1/2/3.html";
//相对路径
String relativePath = "../../a.jpg";
//以下方法对相对路径进行转换
URL absoluteUrl = new URL(absolutePath);
URL parseUrl = new URL(absoluteUrl ,relativePath );
//最终结果
log.info("相对路径转换后的绝对路径:" + parseUrl .toString());
展示了一些例子:
public void test1() {
//绝对路径
String absolutePath = "http://www.aaa.com/1/2/3.html";
//相对路径
String relativePath = "../../a.jpg"; //http://www.aaa.com/a.jpg
//但是设置往上3层时,即"../../../a.jpg",输出了http://www.aaa.com/../a.jpg
//relativePath = "a.jpg";
//http://www.aaa.com/1/2/a.jpg
//relativePath = "3/4/5.jpg";
//http://www.aaa.com/1/2/3/4/5.jpg
//relativePath = "https://www.baidu.com";
//输出:https://www.baidu.com
//以下方法对相对路径进行转换
URL absoluteUrl = null;
try {
absoluteUrl = new URL(absolutePath);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
System.out.println("参考的绝对地址格式不正确");
e.printStackTrace();
}
URL parseUrl = null;
try {
parseUrl = new URL(absoluteUrl ,relativePath );
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//最终结果
System.out.println("相对路径转换后的绝对路径:" + parseUrl .toString());
}
- 比较方便的是,可以识别“../../c.jpg”类似的相对路径
- 如果输入的相对路径是合法的完整路径,则直接返回该路径
- 如果绝对路径本身不是合法的,则抛出异常,可自行添加处理的代码