2013-01-03 56 views
2

您能否幫我找到解決此問題的解決方案?在Windows中製作Java Swing接受用戶輸入路徑(從資源管理器複製粘貼路徑)

我試圖與Swing組件一個Java GUI

接口應該接受Windows路徑到一個特定的文件,並觸發一系列功能上的文件按下提交按鈕後

現在,我已經創建的組件,以獲取用戶輸入爲:

JTextField introducedPath1 = new JTextField(50); 

我試圖改變通過複製粘貼從資源管理器的路徑獲得的默認Windows路徑爲接受的文件路徑:

File file; 
String makeCanonicalPath=introducedPath1.getText().toString(); 
      makeCanonicalPath=makeCanonicalPath.replaceAll("\\", "/"); 
      file = new File(makeCanonicalPath); 

但我不斷收到此錯誤:

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

\ 
^ 
at java.util.regex.Pattern.error(Unknown Source) 
at java.util.regex.Pattern.compile(Unknown Source) 
at java.util.regex.Pattern.<init>(Unknown Source) 

我假設它是由默認路徑在Windows引起的(例如:L:\實踐\測試)得到它「\」解釋爲逃逸序列。

任何幫助或建議,可以理解

+0

如果使用拖放操作,則可以獲取FileList並獲取實際的File對象。沒有必要用字符串猴子。例如,請查看我的代碼:[拖放示例](http://stackoverflow.com/a/13597312/522444) –

回答

3

用的replaceAll,你需要使用的Java轉義正則表達式,所以

makeCanonicalPath.replaceAll("\\\\", "/"); 

因爲它不是一個文本搜索替換,但正則表達式一個。

例如,如果您想要基於文本的搜索替換,請使用apache commonsstring replace

另外,一種替代方法是使用replace() - http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#replace(char,char)而不是replaceAll - 它會在不使用正則表達式的情況下替換所有的事件,並且由於您只有一個字符來替換,所以它會工作。

+0

爲什麼使用apache commons字符串替換時,makeCanonicalPath.replaceAll(「 \\\\「,」/「);工作? apache commons string取代了更好的做法嗎? – user1944955

+0

@ user1944955如果您想進行基於文本的替換,最好使用某種文本替換機制。如果你真的想要正則表達式,那麼一定要使用它。但它看起來不像你呢? – eis

+0

with replace()我的解決方案如下所示:String makeCanonicalPath1 = introduPath1.getText()。replace(「\\」,「/」)。toString(); file = new File(makeCanonicalPath1);由於文件請求字符串作爲輸入。所以我不確定這是否是一個更好的解決方案。是嗎? – user1944955

相關問題