2012-07-16 47 views
2

我試圖用java(Android)中的'/'替換'\\',這似乎不起作用!在Java中用「/」替換「\」

String rawPath = filePath.replace("\\\\", "/"); 

這是什麼問題?我已經逃脫了「\」並嘗試轉義'/',但沒有用。原始字符串沒有任何反應。

filePath = abc\\xyz(not after escaping two \\, the original string is with two \\) 
    rawPath = abc \ xyz 
    expected = abc/xyz 

這樣做的正確方法是什麼? (另一個Windows文件到Android路徑轉換概率)

+3

爲什麼不在整個代碼中使用'java.io.File.separator'? – 2012-07-16 17:38:56

+0

是的 - 切換到這個,只是現在測試一些東西,跑到這裏,謝謝! – Slartibartfast 2012-07-16 17:45:12

回答

12

當使用String.replace(String, String)反斜槓不需要轉義兩次(使用replaceAll時這就是 - 它正則表達式待遇)。所以:

String rawPath = filePath.replace("\\", "/"); 

或者使用char版本:

String rawPath = filePath.replace('\\', '/'); 
+0

反斜槓總是需要在java中轉義。這與正則表達式無關。你的建議將用'/'替換每個'\\'。 – assylias 2012-07-16 17:37:36

+0

字符串中的反斜槓總是需要在代碼中轉義,除非您打算將它用作其他轉義序列的一部分。 – pb2q 2012-07-16 17:38:27

+3

...當然...(這就是爲什麼我寫了'replaceAll'的評論) – dacwe 2012-07-16 17:38:39

6

你不需要四druple逃生,

\\\\

,只是單純的

\ \

6

用單斜線轉義應該就夠了。以下工作適合我。

String rawPath = filePath.replace("\\", "/");

2

如果你想在你的原始字符串用單正斜槓來代替2個反斜線序列,這應該工作:

String filePath = "abc\\\\xyz"; 
String rawPath = filePath.replace("\\\\", "/"); 

System.out.println(filePath); 
System.out.println(rawPath); 

輸出:

abc\\xyz 
abc/xyz 
3
public static void main(String[] args) { 
    String s = "foo\\\\bar"; 
    System.out.println(s); 
    System.out.println(s.replace("\\\\", "/"));  
} 

將打印

foo\\bar 
foo/bar 
1

你真的有在String兩個反斜槓擺在首位?這隻出現在Java源代碼中。在運行時只會有一個反斜槓。所以,這項任務會縮減爲將反斜槓更改爲正斜槓(爲什麼?)。如果你正在使用replaceAll(),你需要一個正則表達式,它需要四個:編譯器兩個,正則表達式兩個,但你沒有使用它,你使用的是replace(),它不是一個正則表達式,所以你只需要兩個,一個用於編譯器,另一個用於自身。

你爲什麼這樣做?根本不需要在Java中的文件路徑中使用反斜槓,也沒有必要將它們翻譯爲/除非您正在使用類似URL的東西,在這種情況下,有File.toURI()方法以及URI和URL類的。