java - 文件路径从\到/

标签 java path

我有这个问题:我从 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/

相关文章:

python - os.path 如何映射到 posixpath.pyc 而不是 os/path.py?

python - open() 给出 FileNotFoundError/IOError : Errno 2 No such file or directory

java - 实现通用接口(interface)

java - 如何仅为特定标记设置 InfoWindowAdapter

java - 不确定我是否为 Eclipse 使用了正确版本的 Java

java - 我如何知道 AmazonS3Client 是否已关闭?

java - 在 gitlab 上测试 jsch 会导致无效私钥错误

python - 在导入之前确定 Python 包位置

bash - 如何删除 Sublime Text 2 使用的现有符号链接(symbolic link)?

iPhone xcode 设备与模拟器的搜索路径?