Zdravim,
nekde jsem kdysi vyguglil a pouzivam toto:
public static File getRelativeDirectory(final File base, final File
file) {
final String relativeFile;
try {
relativeFile = getRelativePath(base, file);
logger.info("Relative path of '" + file + "' to " + base + " is
" + relativeFile);
} catch (IOException e) {
return file;
}
if (relativeFile == null)
return file;
else return new File(relativeFile);
}
private static String getRelativePath(final File base, final File file)
throws IOException {
String basePath;
String filePath = file.getCanonicalPath();
if (base.isFile()) {
File baseParent = base.getParentFile();
if (baseParent == null) {
return null;
}
basePath = baseParent.getCanonicalPath();
} else {
basePath = base.getCanonicalPath();
}
if (!basePath.endsWith(File.separator)) {
basePath += File.separator;
}
int p = basePath.indexOf(File.separatorChar);
String prefix = null;
while (p != -1) {
String newPrefix = basePath.substring(0, p + 1);
if (!filePath.startsWith(newPrefix)) {
break;
}
prefix = newPrefix;
p = basePath.indexOf(File.separatorChar, p + 1);
}
if (prefix == null) {
return null;
}
filePath = filePath.substring(prefix.length());
if (prefix.length() == basePath.length()) {
return filePath;
}
int c = 0;
p = basePath.indexOf(File.separatorChar, prefix.length());
while (p != -1) {
c++;
p = basePath.indexOf(File.separatorChar, p + 1);
}
for (int i = 0; i < c; i++) {
filePath = ".." + File.separator + filePath;
}
return filePath;
}
-Vity
> -----Original Message-----
> From: [email protected]
> [mailto:[email protected]] On Behalf Of Richard Holly
> Sent: Tuesday, February 03, 2009 12:39 PM
> To: Java
> Subject: Re: Relativni a absolutni File
>
> Lukáš Zapletal wrote / napísal(a):
> > Zdravim,
> >
> > potreboval bych vytvaret a pracovat s relativnimi cestami
> pomoci File
> > vzhledem k jinemu adresari, nez je HOME na UNIXU resp.
> working dir na
> > Windows. Bohuzel z dokumentace o File vyplyva, ze se s relativnimi
> > cestami da pracovat pouze vzhledem k tomuto adresari. Jine moznosti
> > opravdu nejsou?
> >
> > Snad jen pres new File(base).toURI().relativize(...) ale to jsou
> > sileny harakiri kvuli jednoduche relativizaci...
> >
> > ps - uz aby tu byla JSR 203
> >
> >
> ak ide len o to pracovat relativne v inom adresari ako $home
> tak napr.
> createTempFile :)
>
>