2012-01-23 24 views
3

的文件路徑我有這個問題:我從JFileChooser中選擇一個文件,如果我打印一個系統,我得到這個路徑:C:\ Users \ Joakim \ Desktop \ dude.txt,當我想要使用此鏈接將此文件複製到另一個位置,我需要這樣的路徑:C://Users/Joakim/Desktop/dude.txt 我該怎麼做?從到/

public void upload(String username) throws RemoteException, NullPointerException{ 
    JFileChooser chooser = new JFileChooser(getProperty + "/desktop/"); 
    int returnVal = chooser.showOpenDialog(parent); 
    if (returnVal == JFileChooser.APPROVE_OPTION) { 
     System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName()); 
    } try { 
     String fileName = chooser.getSelectedFile().getName(); 
     System.out.println(fileName); //name of the file 
     File selectedFile = chooser.getSelectedFile(); 
     System.out.println(selectedFile); //path of the file 
     //File path= selectedFile.replaceAll('/','/'); 
     String serverDirectory = ("C://Users/Joakim/Dropbox/Project RMI/SERVER/"); 
     byte[] filedata = cf.downloadFile(selectedFile); 
     BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(serverDirectory + fileName)); 
     output.write(filedata, 0, filedata.length); 
     output.flush(); 
     output.close(); 
    } catch (Exception e) { 
     System.err.println("FileServer exception: " + e.getMessage()); 
     e.printStackTrace(); 
    } 
} 

感謝提前:)

編輯:所以這沒有工作了,因爲我刨。我想改變路徑到C://Users/Joakim/Desktop/dude.txt,但那還不夠。我需要//CUsers/Joakim/Desktop/dude.txt。我現在遇到的問題是要獲取它,並仍將其用作文件。我做了測試

File newFil = new File("//" + selectedFile); 
byte[] filedata = cf.downloadFile(nyFil); 

這對我不起作用。我仍然出去C://Users/Joakim/Desktop/dude.txt 有人有一兩個? :)

+0

嘗試,如果你真的有,爲什麼不直接通過更換'\''/'的字符串? – tim

+0

註釋掉了嗎?取消註釋,並用''\\''替換第一個參數。並用兩個'em'替換'/'的第一個實例。 – bdares

+0

*「C:\ Users \ Joakim \ Desktop \ dude.txt當我想使用此鏈接將此文件複製到另一個位置時,我需要這樣的路徑:C:// Users/Joakim/Desktop/dude .txt「*爲什麼您需要將其轉換爲不正確的路徑版本?如果您控制使用該信息的代碼,則應該修復該代碼。如果您不控制使用該代碼的代碼,請提出錯誤報告。 –

回答

2

很簡單,試試這個:

String first = "C:\\Mine\\Java"; 
String second = first.replace("\\", "/"); 
second = second.replaceFirst("/", "//"); 
System.out.println(second); 

OUTPUT:

OUTPUT PATH 希望這會以某種方式幫助。

問候

1

這應該工作:C:\用戶使用雙\

3

你真的應該使用系統屬性file.separator

字符分隔文件路徑的組件。這是在UNIX上的 和Windows上的「\」上的「/」。

String fileSeparator = System.getProperty("file.separator"); 

您也可以訪問該文件分隔符爲File.separator

考慮分手的路徑結合使用該財產的替代向前或向後斜槓。

1

與此

/** 
* Prepare dropbox path from the path. 
* 
* @param path 
    *   that is to be formated. 
* @return 
    *  Return dropbox formated path. 
*/ 
public static String createDropboxPathFormat(String path) { 

    // Replaced all \ with/of the path. 
    String dropboxPath = path.replaceAll("[\\\\]", "/"); 

    // Finally replaced all // with/
    dropboxPath = dropboxPath.replaceAll("[//]", "/"); 
    return dropboxPath; 
}