Aquí es el código de ejemplo que funciona para mí.
public String absolutePath(String relative, String absoluteTo)
{
String[] absoluteDirectories = relative.split("\\\\");
String[] relativeDirectories = absoluteTo.split("\\\\");
int relativeLength = relativeDirectories.length;
int absoluteLength = absoluteDirectories.length;
int lastCommonRoot = 0;
int index;
for (index = 0; index < relativeLength; index++)
if (relativeDirectories[index].equals("..\\\\"))
lastCommonRoot = index;
else
break;
StringBuilder absolutePath = new StringBuilder();
for (index = 0; index < absoluteLength - lastCommonRoot; index++)
{
if (absoluteDirectories[index].length() > 0)
absolutePath.append(absoluteDirectories[index] + "\\\\");
}
for (index = lastCommonRoot; index < relativeLength - lastCommonRoot;
index++)
{
if (relativeDirectories[index].length() > 0)
absolutePath.append(relativeDirectories[index] + "\\\\");
}
return absolutePath.toString();
}
también que la conversión al respecto:
public String relativePath(String absolute, String relativeTo) throws Exception
{
String[] absoluteDirectories = absolute.split("\\\\");
String[] relativeDirectories = relativeTo.split("\\\\");
int length = absoluteDirectories.length < relativeDirectories.length ?
absoluteDirectories.length : relativeDirectories.length;
int lastCommonRoot = -1;
int index;
for (index = 0; index < length; index++)
if (absoluteDirectories[index].equals(relativeDirectories[index]))
lastCommonRoot = index;
else
break;
if (lastCommonRoot > -1){
StringBuilder relativePath = new StringBuilder();
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.toString();
}
else{
throw new Exception("No common root found between working direcotry and filename");
}
}
** tl; dr respuesta:. ** nuevo archivo ("mi/ruta") getCanonicalPath() – Andrew