2013-07-12 78 views
0

我試圖將我的java程序轉移到Linux中的windows,並且正在獲取文件路徑的各種問題。在Java中的文件路徑中轉義反斜槓

最新的問題是這樣的:

public void restoreCorrections(File correctionDir) {

String filePath = correctionDir.getPath().replaceFirst("Backup" + File.separator + "Corrections" + File.separator, 
      "Data" + File.separator + "Matches" + File.separator);  System.out.println(filePath); 

      .... 
} 

此功能是通過多次與從特定文件夾(備份\勘誤的內容)的每個文件循環。

我提示以下錯誤:

Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence near index 7 Backup\Corrections\ ^ at java.util.regex.Pattern.error(Unknown Source)

我已經嘗試添加 的replaceAll( 「\\」, 「\\\\」)後的getPath(),也的replaceAll(文件分割符,「\\」)

但他們都結束了一個類似的錯誤:

Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1 \ ^

任何人有任何想法是怎麼回事?

回答

0

嘗試在第一參數替換反斜槓replaceFirst

String filePath = correctionDir.getPath().replaceFirst(("Backup" + File.separator + "Corrections" + File.separator).replaceAll("\", "\\"), 
     "Data" + File.separator + "Matches" + File.separator); 

即參數是一個正則表達式和被切換到一個Pattern

另外,如果分隔符是反斜槓,則只需要用雙精度替換反斜槓。如果它的斜線(如在Windows中)然後離開它。

你也可以使用非正則表達式的解決方案:

String original = "Backup" + File.separator + "Corrections" + File.separator; 
int col = correctionDir.indexOf(original); 
String filePath = correctionDir.substring(0, col) + "Data" + File.separator + "Matches" + File.separator + correctionDir.substring(col + original.length()); 
+0

非正則表達式的方式完美的作品,謝謝! –

+0

您是否知道如果您使用斜槓來劃分路徑部分,Windows將會非常高興?對於UNC路徑的網絡部分有一些使用反斜線,雖然...也許你需要「\\ Server1」部分有一個反斜槓。我只是不記得那裏的問題。即使如此,其他人也可以使用斜槓。 –

相關問題