001 package jp.osdl.jbento2; 002 003 import java.io.File; 004 005 public class PathUtils { 006 007 public static String calculateRelativePath(File path1, File path2) { 008 String path1Str = formatPath(path1.getAbsolutePath()); 009 String path2Str = formatPath(path2.getAbsolutePath()); 010 011 int index = 0; 012 while (index < path2Str.length() && index < path1Str.length() 013 && path2Str.charAt(index) == path1Str.charAt(index)) { 014 index++; 015 } 016 path2Str = path2Str.substring(index); 017 path1Str = path1Str.substring(index); 018 019 StringBuffer result = new StringBuffer(); 020 if (path1Str.length() != 0) { 021 for (int i = 0; i < path1Str.length(); i++) { 022 if (path1Str.charAt(i) == '/') { 023 result.append("../"); 024 } 025 } 026 } 027 result.append(path2Str); 028 return result.toString(); 029 } 030 031 public static String formatPath(String path) { 032 String result = path.replace(File.separatorChar, '/'); 033 if (result.charAt(result.length() - 1) != '/' 034 && new File(path).isDirectory()) { 035 result = result + "/"; 036 } 037 return result; 038 } 039 040 public static String basename(File f, String ext) { 041 String name = f.getName(); 042 int i = name.lastIndexOf(ext); 043 if (i != -1) { 044 return name.substring(0, i); 045 } else { 046 return name; 047 } 048 } 049 }