字符串/路径比较
问题描述:
我对Java程序并不熟悉。 java的路径比较和字符串能够完成下面列出的任务吗?字符串/路径比较
Path a = Paths.get("C:/Folder/");
Path b = Paths.get("C:/Folder/abc/def/");
会不会有任何方法来做两种路径的比较并检索只有两个路径之间的差异。例如,如果我比较a
和b
,我可以检测到/abc/def/
与两个路径的主要区别,并将其存储到新变量中。我曾尝试寻找一些代码网上,但不幸的是我得到的例子是确定路径的相似性,并返回结果yes
或not
仅
答
使用StringUtils
从Apache Common API到diff string
。
下面是一些从文档的例子:
StringUtils.difference("ab", "abxyz") = "xyz"
StringUtils.difference("abcde", "abxyz") = "xyz"
StringUtils.difference("abcde", "xyz") = "xyz"
从Path
获取String
和difference
:
String a = Paths.get("C:/Folder/").toString();
String b = Paths.get("C:/Folder/...").toString();
String diff = StringUtils.difference(a, b);
答
一种方法是使用基本的Java字符串的方法来确定一个路径由其它进行遏制。如果是这样,然后采取包含路径的额外子字符串。考虑以下方法:
public String findPathDiff(String patha, String pathb) {
String diff = "";
if (pathb.contains(patha)) {
diff = pathb.substring(patha.length() - 1);
}
else if (patha.contains(pathb)) {
diff = patha.substring(pathb.length() - 1);
}
}
用法:
String patha = "C:/Folder/";
String pathb = "C:/Folder/abc/def/";
String diff = findPathDiff(patha, pathb);
System.out.println(diff)
这将输出/abc/def/
为两个路径之间的差异。
答
只需使用
a.relativize(b)
其结果将是: “abc \ def \”
答
您可以使用以下StringUtils.difference(String a,String b) of org.apache.commons.lang.StringUtils。
Path a = Paths.get("C:/Folder/");
Path b = Paths.get("C:/Folder/abc/def/");
System.out.println(StringUtils.difference(a.toString(),b.toString());
你有没有花时间做一些研究?尝试['Path#relativize()'](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html#relativize-java.nio.file.Path-) –
@JimGarrison我刚刚学到了一些东西。我使用核心字符串方法给出了一个答案,但我猜Java已经涵盖了这个。 –
如何将此标记为http://stackoverflow.com/questions/204784/how-to-construct-a-relative-path-in-java-from-two-absolute-paths-or-urls的副本? – 2017-01-10 06:33:48