Gets the path relative to the specified base directory. @param absolutePath the absolute path @param base the absolute base directory path @return (with forward slashes) the path relative to the base, or the absolutePath if no relative path is found (eg, different drive) or the absolutePath if
(String absolutePath, String base)
| 331 | * or the absolutePath if it is really a relative path |
| 332 | */ |
| 333 | public static String getPathRelativeTo(String absolutePath, String base) { |
| 334 | // if no base specified then base is current user directory |
| 335 | if((base==null)||base.equals("")) { //$NON-NLS-1$ |
| 336 | base = getUserDirectory(); |
| 337 | } |
| 338 | // make sure both paths use forward slashes |
| 339 | absolutePath = forwardSlash(absolutePath); |
| 340 | base = forwardSlash(base); |
| 341 | // return absolutePath if either path not absolute |
| 342 | if(!absolutePath.startsWith("/")&&(absolutePath.indexOf(":")==-1)) { //$NON-NLS-1$ //$NON-NLS-2$ |
| 343 | return absolutePath; |
| 344 | } |
| 345 | if(!base.startsWith("/")&&(base.indexOf(":")==-1)) { //$NON-NLS-1$ //$NON-NLS-2$ |
| 346 | return absolutePath; |
| 347 | } |
| 348 | // look for paths in jar files |
| 349 | int jar = absolutePath.indexOf("jar!"); //$NON-NLS-1$ |
| 350 | if(jar>-1) { |
| 351 | absolutePath = absolutePath.substring(jar+5); |
| 352 | return absolutePath; |
| 353 | } |
| 354 | // construct relative path |
| 355 | String relativePath = ""; //$NON-NLS-1$ |
| 356 | // search for base up containing hierarchy |
| 357 | if(base.endsWith("/")) { //$NON-NLS-1$ |
| 358 | base = base.substring(0, base.length()-1); |
| 359 | } |
| 360 | for(int j = 0; j<6; j++) { |
| 361 | // move base up one level each iteration after the first |
| 362 | if(j>0) { |
| 363 | int k = base.lastIndexOf("/"); //$NON-NLS-1$ |
| 364 | if(k!=-1) { |
| 365 | base = base.substring(0, k); // doesn't include the slash |
| 366 | relativePath += "../"; //$NON-NLS-1$ |
| 367 | } else if(!base.equals("")) { //$NON-NLS-1$ |
| 368 | base = ""; //$NON-NLS-1$ |
| 369 | relativePath += "../"; //$NON-NLS-1$ |
| 370 | } else { |
| 371 | break; // no more levels |
| 372 | } |
| 373 | } |
| 374 | // construct and return relative path once base is in the path |
| 375 | if(!base.equals("")&&absolutePath.startsWith(base)) { //$NON-NLS-1$ |
| 376 | String path = absolutePath.substring(base.length()); |
| 377 | // eliminate leading slash, if any |
| 378 | int k = path.indexOf("/"); //$NON-NLS-1$ |
| 379 | if(k==0) { |
| 380 | path = path.substring(1); |
| 381 | } |
| 382 | relativePath += path; |
| 383 | return relativePath; |
| 384 | } |
| 385 | } |
| 386 | // relative path not found |
| 387 | return absolutePath; |
| 388 | } |
| 389 | |
| 390 | /** |
no test coverage detected