首页 > 解决方案 > 在java中的目录路径中添加单个正斜杠或双反斜杠

问题描述

我正在使用 JFileChooser 在我的项目中获取目录路径。它运行良好,但有一个小问题。假设这是目录结构:

->Home
  ->Documents
    ->Java

这是代码:

JFileChooser fileChooser=new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int userSelection=fileChooser.showSaveDialog(this);
        if(userSelection==JFileChooser.APPROVE_OPTION){
            try{File fileTosave=fileChooser.getSelectedFile();
                File newFile=new File(fileTosave.getAbsolutePath()+"satish.txt");
                System.out.println(newFile);
                this.dispose();}
            catch(Exception e){}
        }

如果当前我在 java 文件夹中,它会给我Home/Documents/JavaWindows 中的路径(或 Home:\Documents\Java)。我想要的是它应该返回包含单正斜杠或双正斜杠(根据平台)的路径,使其看起来像Home/Documents/Java/. 我想这样做是因为稍后我必须在此路径中附加一个文件名,以便文件路径变为Home/Documents/java/file.txt.

关于如何做到这一点的任何想法?

我不想手动添加斜线,因为那样我还必须牢记平台。

谢谢!

标签: javaswingfilepathjfilechooser

解决方案


利用java.io.File.pathSeparator

/**
     * The system-dependent path-separator character, represented as a string
     * for convenience.  This string contains a single character, namely
     * <code>{@link #pathSeparatorChar}</code>.
     */
    public static final String pathSeparator = "" + pathSeparatorChar;

您的代码应如下所示

JFileChooser fileChooser=new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int userSelection=fileChooser.showSaveDialog(this);
        if(userSelection==JFileChooser.APPROVE_OPTION){
            try{File fileTosave=fileChooser.getSelectedFile();
                File newFile=new File(fileTosave.getParent() + File.separator +"satish.txt");
                System.out.println(newFile);
                this.dispose();}
            catch(Exception e){}
        }

推荐阅读