2012-07-15 39 views
10

我正在Windows上開發Scala應用程序,並且需要將文件的路徑插入到HTML模板中。我使用Java的ionio來處理文件和路徑。具有特定路徑分隔符的Java的File.toString或Path.toString

/* The paths actually come from the environment. */ 
val includesPath = Paths.get("foo\\inc") 
val destinationPath = Paths.get("bar\\dest") 

/* relativeIncludesPath.toString == "..\\foo\\inc", as expected */ 
val relativeIncludesPath = destinationPath.relativize(includesPath) 

的問題是,relativeIncludesPath.toString輸出包含反斜槓\作爲分隔符 - 因爲應用程序在Windows上運行 - 但由於路徑被插入到HTML模板,它必須包含正斜槓/代替。

由於在文檔中找不到file/path.toStringUsingSeparator('/')之類的東西,我現在正在幫助自己,我覺得這很不吸引人。

問題:真的沒有比使用替換更好的方法嗎?

我也嘗試過使用Java的URI,但它的relativizeincomplete

+0

也許我錯過了一些東西。爲什麼你不能相對路徑,然後使用'toURI()'而不是'toString()'? – Gene 2012-07-15 18:03:47

+0

我試過了,但後來我得到了一個絕對URI,它看起來像這樣:''file:/ C:/ root/dir/foo/inc /''。 – 2012-07-15 18:36:02

+0

感謝您提及'URI'。我沒有意識到它可以'解決',事實證明它對我來說是完美的。 – 2013-06-06 11:36:32

回答

4

的Windows實現路徑接口存儲路徑內部的一個字符串(至少在OpenJDK implementation)和簡單在調用toString()時返回該表示。這意味着不涉及計算,並且沒有機會「配置」任何路徑分隔符。

因此,我認爲您的解決方案是當前解決問題的最佳選擇。

0

您可以在Java中獲取大部分系統屬性。看看這個鏈接:

http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

你想這樣的:

Key: "file.separator" 
Meaning: Character that separates components of a file path. This is "/" on UNIX and "\" on Windows. 

String sep = System.getProperty("path.separator"); 
+0

我知道我可以得到分隔符,如果我沒有弄錯的話,我甚至可以在全局設置它。但是,我正在尋找一種方法來爲單個操作或單個文件/路徑對象選擇特定的分隔符。 – 2012-07-15 18:34:03

1

我剛碰到這個問題。如果您有相對路徑,則可以使用Path是其元素的Iterable<Path>這一事實,然後是可選的初始根元素,然後可以使用正斜槓將它們自己連接起來。不幸的是,根元素可能包含斜槓,例如在Windows中,您可以獲得像c:\\\foo\bar\(對於UNC路徑)這樣的根元素,所以無論如何您仍然需要用正斜槓代替它。但是,你可以做這樣的事情......

static public String pathToPortableString(Path p) 
{ 
    StringBuilder sb = new StringBuilder(); 
    boolean first = true; 
    Path root = p.getRoot(); 
    if (root != null) 
    { 
     sb.append(root.toString().replace('\\','/')); 
     /* root elements appear to contain their 
     * own ending separator, so we don't set "first" to false 
     */    
    } 
    for (Path element : p) 
    { 
     if (first) 
      first = false; 
     else 
      sb.append("/"); 
     sb.append(element.toString()); 
    } 
    return sb.toString();   
} 

,當我使用此代碼測試:

static public void doit(String rawpath) 
{ 
    File f = new File(rawpath); 
    Path p = f.toPath(); 
    System.out.println("Path: "+p.toString()); 
    System.out.println("  "+pathToPortableString(p)); 
} 

static public void main(String[] args) { 
    doit("\\\\quux\\foo\\bar\\baz.pdf"); 
    doit("c:\\foo\\bar\\baz.pdf"); 
    doit("\\foo\\bar\\baz.pdf"); 
    doit("foo\\bar\\baz.pdf"); 
    doit("bar\\baz.pdf"); 
    doit("bar\\"); 
    doit("bar"); 
} 

我得到這個:

Path: \\quux\foo\bar\baz.pdf 
     //quux/foo/bar/baz.pdf 
Path: c:\foo\bar\baz.pdf 
     c:/foo/bar/baz.pdf 
Path: \foo\bar\baz.pdf 
     /foo/bar/baz.pdf 
Path: foo\bar\baz.pdf 
     foo/bar/baz.pdf 
Path: bar\baz.pdf 
     bar/baz.pdf 
Path: bar 
     bar 
Path: bar 
     bar 

的文本替換正斜槓的反斜槓肯定更容易,但我不知道它是否會打破一些迂迴邊緣的情況。 (Unix路徑中是否有反斜槓?)