3

これは一見単純な問題ですが、私はそれをきれいに行うのに苦労しています。私は次のようなファイルパスを持っています:

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

私が必要としているのは、上記のパスから/ of / my / fileを抽出することです。これは、私の相対パスだからです。

私がそれをすることを考えている方法は次のとおりです:

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で提供されたパスからサブパスを抽出するより良い方法を提案できますか?

ありがとう

4

2 に答える 2

11

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ます。

于 2012-03-22T16:53:32.250 に答える
1

純粋な文字列操作を使用し、基本パスを知っていると仮定し、基本パスの下の相対パスのみが必要で、「../」シリーズを先頭に追加しないと仮定します。

String basePath = "/this/is/an/absolute/path/to/the/location/";
String absolutePath = "/this/is/an/absolute/path/to/the/location/of/my/file";
if (absolutePath.startsWith(basePath)) {
    relativePath = absolutePath.substring(basePath.length());
}

Fileまたはなどのパスロジックを認識するクラスでこれを行うより良い方法は確かにありURIます。:)

于 2012-03-22T16:59:35.060 に答える