2011-08-23 126 views
38

我在寫一個簡單的命令行Java實用程序。我希望用戶能夠使用~運算符傳入相對於其主目錄的文件路徑。所以像~/Documents/...如何在文件路徑中處理〜

我的問題是有沒有辦法讓Java自動解決這種類型的路徑?或者我需要掃描~運算符的文件路徑嗎?

看來這種類型的功能應該烘焙到File對象中。但它似乎不是。

+1

的OS(S)適合您的效用? –

回答

50

一個簡單path = path.replaceFirst("^~",System.getProperty("user.home"));當它從用戶得到(製作File之前它)應該足以在大多數情況下工作。

+5

大多數(所有?)shell只會在argumetn *開始時執行替換*'〜'。例如,路徑'/ a /〜/ c/d.txt'將被完全解釋爲由bash寫入。 –

+0

@andrzej好然後petr的解決方案更好,但是我的結構更緊湊 –

+14

只要注意,這真的不能一直工作。 「〜otheruser/Documents」也是一個有效的主目錄;但是,對於其他用戶的「user.home」而言,不是「user.home」。另外,如果代字號是路徑的目錄部分中的第一個字符,則它只會擴展到主目錄。儘管非常規,「a〜」是與主目錄無關的有效文件。 –

26

這是特定於shell的擴展,所以你需要在該行的開頭來取代它,如果存在的話:

String path = "~/xyz"; 
... 
if (path.startsWith("~" + File.separator)) { 
    path = System.getProperty("user.home") + path.substring(1); 
} 

File f = new File(path); 
... 
+4

不應該是'System.getProperty(「user.home」)+ path.substring(2);' –

+0

是的,謝謝,修正 –

8

正如Edwin Buck在評論中指出的另一個答案,〜otheruser/Documents也應該正確擴展。下面是爲我工作的函數:

public String expandPath(String path) { 
    try { 
     String command = "ls -d " + path; 
     Process shellExec = Runtime.getRuntime().exec(
      new String[]{"bash", "-c", command}); 

     BufferedReader reader = new BufferedReader(
      new InputStreamReader(shellExec.getInputStream())); 
     String expandedPath = reader.readLine(); 

     // Only return a new value if expansion worked. 
     // We're reading from stdin. If there was a problem, it was written 
     // to stderr and our result will be null. 
     if (expandedPath != null) { 
      path = expandedPath; 
     } 
    } catch (java.io.IOException ex) { 
     // Just consider it unexpandable and return original path. 
    } 

    return path; 
} 
+1

由於它依賴於ls,因此Dave M提供的expandPath方法僅在路徑存在時纔有效。 – sfosdal

+1

+1爲此啓動一個新流程似乎是一個巨大的矯枉過正,但它可能是唯一「正確」的方式。 – minexew

4

與實際路徑〜作品人物在其中一個相當精簡的回答:

String path = "~/Documents"; 
path.replaceFirst("^~", System.getProperty("user.home")); 
+0

這與@ ratchet的答案有同樣的缺陷:'〜foo'將被替換爲'/ home/yournamefoo'而不是'/ home/foo'。 – bfontaine

相關問題