从绝对路径中提取相对路径 [英] Extracting relative paths from absolute paths

查看:126
本文介绍了从绝对路径中提取相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个看似简单的问题,但是我很难以一种干净的方式来做.我的文件路径如下:

This is a seemingly simple problem but I am having trouble doing it in a clean manner. I have a file path as follows:

/this/is/an/absolute/path/to/the/location/of/my/file

/this/is/an/absolute/path/to/the/location/of/my/file

我需要的是从上述给定路径中提取/of/my/file,因为那是我的相对路径.

What I need is to extract /of/my/file from the above given path since that is my relative path.

我的想法如下:

String absolutePath = "/this/is/an/absolute/path/to/the/location/of/my/file";
String[] tokenizedPaths = absolutePath.split("/");
int strLength = tokenizedPaths.length;
String myRelativePathStructure = (new StringBuffer()).append(tokenizedPaths[strLength-3]).append("/").append(tokenizedPaths[strLength-2]).append("/").append(tokenizedPaths[strLength-1]).toString();

这可能会满足我的迫切需求,但是有人可以建议一种从Java所提供的路径中提取子路径的更好方法吗?

This will probably serve my immediate needs but can somebody suggest a better way of extracting sub-paths from a provided path in java?

谢谢

推荐答案

使用 URI类:

URI base = URI.create("/this/is/an/absolute/path/to/the/location");
URI absolute =URI.create("/this/is/an/absolute/path/to/the/location/of/my/file");
URI relative = base.relativize(absolute);

这将导致of/my/file.

这篇关于从绝对路径中提取相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆