首页 文章

如何在Java中使用双反斜杠获取文件路径

提问于
浏览
-2

我有一个程序,我在.txt文件中保存学校成绩 . 我想让用户选择保存此文件的位置 . 它适用于JFileChooser查找但Java存在FilePath问题 . 来自JFileChooser的文件路径如下所示:C:\ Users ... \ Documents \ n.txt但是如果我想读取Program Java中的TextFile,则说它无法找到Filepath . 它应如下所示:C:\ Users \ ... \ Documents \ n.txt

如何使用双反斜杠获取路径?

public void actionPerformed(ActionEvent e) {

            JFileChooser jf = new JFileChooser();
            jf.showSaveDialog(null);
            String fPath = jf.getSelectedFile().getPath();
            fPath.replaceAll('\', '\\');

            System.out.println(p);

        }

这不起作用它说无效的字符常量

4 回答

  • 0

    有些地方反斜杠用作转义字符,必须转义,只是Windows路径分隔符的反斜杠 .

    这些地方是.properties文件,java字符串文字等等 .

    您可以为Windows路径使用斜杠(Windows的POSIX兼容性) .

    fPath = fPath.replace('\\', '/');
    

    反斜杠:

    fPath = fPath.replace("\\", "\\\\");
    

    解释是必须转义char和字符串文字中的单个反斜杠:两个反斜杠表示单个反斜杠 .

    使用正则表达式(replaceAll),可以使用间隙作为命令:数字表示为 \d ,表示为java字符串: "\\d" . 因此反斜杠本身变成(看哪):

    fPath = fPath.replaceAll("\\\\", "\\\\\\\\"); // PLEASE NOT
    

    I almost did not see it, but methods on String do not alter it, but return a new value, so one needs to assign the result.

  • 1

    您的代码中存在多个问题:

    public void actionPerformed(ActionEvent e) {
    
            JFileChooser jf = new JFileChooser();
            jf.showSaveDialog(null);
            String fPath = jf.getSelectedFile().getPath();
            // fPath is a proper file path. This can be used directly with
            // new File(fPath). The contents will contain single \ character
            // as Path separator
            fPath.replaceAll('\', '\\');
            // I guess you are trying to replace a single \ character with \\
            // character. You need to escape the \ character. You need to
            // consider that both parameters are regexes.
            // doing it is:
            // fPath.replaceAll("\\\\", "\\\\\\\\");
            // And then you need to capture the return value. Strings are 
            // immutable in java. So it is:
            // fPath = fPath.replaceAll("\\\\", "\\\\\\\\");
            System.out.println(p);
            // I don't know what p is. I guess you want to use fPath
        }
    

    也就是说,我不明白你为什么要转换 JFileChooser 返回的路径 .

  • 0

    在Java中使用硬编码文件名时,应始终使用正斜杠 / 作为文件分隔符 . Java知道如何在Windows上处理它们 .

    您也不应该使用绝对路径 . 您不知道目标系统上是否存在这些路径 . 您应该使用以类路径开头的相对路径作为根"/..."或从 System.getProperty() https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#getProperties--获取一些系统相关的位置

  • 1

    您不需要Java中带有双反斜杠的文件路径 . 双反斜杠用于:

    • Java编译器,在字符串文字中 .

    • Java正则表达式编译器 .

    在其他任何地方,您都可以获得反斜杠,或使用正斜杠 .

    可能你在寻找 java.util.Properties

相关问题