'개발이야기/Java'에 해당되는 글 1건

  1. 두 절대경로에서 상대경로 구하기

두 절대경로에서 상대경로를 구하는 JAVA 코드입니다.

  • fromPath : C:\Windows\System32\drivers\etc
  • toPath : C:\Program Files
  • Result : ../../../../Program Files
/**
 * fromPath 절대경로에서 toPath 절대경로에 대한 상대경로를 반환
 * 
 * @param fromPath 절대경로
 * @param toPath 절대경로
 * @return 상대경로
 */
public static String makeRelativePath(String fromPath, String toPath) {
 
	if( fromPath == null || fromPath.isEmpty() ) 	return null;
	if( toPath == null || toPath.isEmpty() ) 		return null;
 
	StringBuilder relativePath = null;
 
	fromPath = fromPath.replaceAll("\\\\", "/"); 
	toPath = toPath.replaceAll("\\\\", "/");
 
	if (fromPath.equals(toPath) == true) {
 
	} else {
		String[] absoluteDirectories = fromPath.split("/");
		String[] relativeDirectories = toPath.split("/");
 
		//Get the shortest of the two paths
		int length = absoluteDirectories.length < relativeDirectories.length ? 
				absoluteDirectories.length : relativeDirectories.length;
 
		//Use to determine where in the loop we exited
		int lastCommonRoot = -1;
		int index;
 
		//Find common root
		for (index = 0; index < length; index++) {
			if (absoluteDirectories[index].equals(relativeDirectories[index])) {
				lastCommonRoot = index;
			} else {
				break;
				//If we didn't find a common prefix then throw
			}
		}
		if (lastCommonRoot != -1) {
			//Build up the relative path
			relativePath = new StringBuilder();
			//Add on the ..
			for (index = lastCommonRoot + 1; index < absoluteDirectories.length; index++) {
				if (absoluteDirectories[index].length() > 0) {
					relativePath.append("../");
				}
			}
			for (index = lastCommonRoot + 1; index < relativeDirectories.length - 1; index++) {
				relativePath.append(relativeDirectories[index] + "/");
			}
			relativePath.append(relativeDirectories[relativeDirectories.length - 1]);
		}
	} 
 
	return relativePath == null ? null : relativePath.toString();
}



references