在我的Java應用程序中,我需要使用JFileChooser選擇路徑。我寫的代碼如下:如何根據操作系統使用JFileChooser在Java中獲取正確路徑
jfChooser = new JFileChooser();
jfChooser.setCurrentDirectory(new java.io.File("."));
jfChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (jfChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
System.out.println("getCurrentDirectory(): "+ jfChooser.getCurrentDirectory());
System.out.println("getSelectedFile() : "+ jfChooser.getSelectedFile());
tfPath.setText(jfChooser.getSelectedFile().getAbsolutePath()); // the selected path set to textfield which is lated get by the program
}
else {
System.out.println("No Selection ");
}
我收到路徑properly.For例子,在這裏我得到的路徑(在Windows操作系統中)
String choosedPath=tfPath.getText().trimm();
現在其實我想以編程方式在給定路徑上(即在新文件夾目錄中)創建另一個目錄。
對於我有新的目錄名稱「NEWDIR」這樣的字符串傳遞到文件的構造函數用於創建這個目錄如下:
File createFolder = new File("choosedPath"+"\\"+"newdir");
現在的問題是,我的應用程序可以在Windows上運行,也可以運行在Linux上,所以根據文件路徑分隔符變化(即'/'的Windows和'\'的Linux)
我如何克服這個問題,以便我得到propper斜槓根據操作系統的路徑?
你應該考慮檢查[格式化沙箱](http://meta.stackexchange.com/questions/3122/formatting-sandbox)並學習如何爲你的下一個問題格式化你的代碼 – justkt 2011-04-18 12:45:17
@ justkt-好的朋友 – 2011-04-18 12:53:05
在Java中,您可以在Windows文件路徑上使用正斜槓,Java將處理它。正如其他人所說的File.Seperator是正確的操作系統agnositc解決方案。儘管你可以隨處使用正斜槓。 – Jberg 2011-04-18 14:24:02