我有这个问题:我从 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 但这还不够。我需要//C://Users/Joakim/Desktop/dude.txt。我现在的问题是得到它并仍然将它用作文件。我试过了
File newFil = new File("//" + selectedFile);
byte[] filedata = cf.downloadFile(nyFil);
这对我不起作用。我仍然退出 C://Users/Joakim/Desktop/dude.txt 有人有一两个小费吗? :)
最佳答案
你真的应该使用系统属性 file.separator
:
Character that separates components of a file path. This is "/" on UNIX and "\" on Windows.
String fileSeparator = System.getProperty("file.separator");
您还可以访问文件分隔符作为 File.separator
考虑分解您的路径以合并使用此属性来代替正斜杠或反斜杠。
关于java - 文件路径从\到/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8976445/