2017-01-10 115 views
0

我對Java程序並不熟悉。 java的路徑比較和字符串能夠完成下面列出的任務嗎?字符串/路徑比較

Path a = Paths.get("C:/Folder/"); 
Path b = Paths.get("C:/Folder/abc/def/"); 



會不會有任何方法來做兩種路徑的比較並檢索只有兩個路徑之間的差異。例如,如果我比較ab,我可以檢測到/abc/def/與兩個路徑的主要區別,並將其存儲到新變量中。我曾嘗試尋找一些代碼網上,但不幸的是我得到的例子是確定路徑的相似性,並返回結果yesnot

+6

你有沒有花時間做一些研究?嘗試['Path#relativize()'](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html#relativize-java.nio.file.Path-) –

+0

@JimGarrison我剛剛學到了一些東西。我使用核心字符串方法給出了一個答案,但我猜Java已經涵蓋了這個。 –

+0

如何將此標記爲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

回答

1

使用StringUtilsApache Common APIdiff string

下面是一些從文檔的例子:

StringUtils.difference("ab", "abxyz") = "xyz" 
StringUtils.difference("abcde", "abxyz") = "xyz" 
StringUtils.difference("abcde", "xyz") = "xyz" 

Path獲取Stringdifference

String a = Paths.get("C:/Folder/").toString(); 
String b = Paths.get("C:/Folder/...").toString(); 
String diff = StringUtils.difference(a, b); 
0

一種方法是使用基本的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/爲兩個路徑之間的差異。

0

只需使用

a.relativize(b) 

其結果將是: 「abc \ def \」

0

您可以使用以下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());