用单反斜杠替换双反斜杠

Rek*_*249 -1 java file path

我有一个路径(例如C:\ Users \ chloe \ Documents),但是当我要将其保存在属性文件中时,由于字符串“ C:\ Users \ chloe \ Documents”,它会以双斜杠保存它由于某些原因,它没有放在\\C:之后。我在互联网上搜索,他们正在谈论replaceAll:

path.replaceAll("/+", "/");
Run Code Online (Sandbox Code Playgroud)

但这代替了常规的斜杠,我想知道如何用反斜杠...(在java中)

这是我写入属性文件的方式(仅需要的内容):

Properties prop = new Properties();
OutputStream output = null;


try {
                output = new FileOutputStream("config.properties");
                prop.setProperty("dir", path);
                prop.store(output, null);
            }catch(IOException e1){
                e1.printStackTrace();
            } finally {
                if (output != null) {
                    try {
                        output.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }

            }

 path = System.getProperty("user.home") + File.separator + "AppData" + File.separator + "Roaming";
Run Code Online (Sandbox Code Playgroud)

Ell*_*sch 5

\\当您用String文字对它进行硬编码时,才需要。因为\转义字符,所以它\在运行时成为单个字符。您也可以/使用分隔符编写路径。要清楚

String path = "C:\\Users\\chloe\\Documents";
Run Code Online (Sandbox Code Playgroud)

创建一个String值等于C:\Users\chloe\Documents(如果您使用过print)的。你也可以写

String path = System.getProperty("user.home") + File.separator + "Documents";
Run Code Online (Sandbox Code Playgroud)

然后Documents在运行时选择用户的文件夹。最后,

System.out.println("\\\\");
System.out.println("\\\\".replaceAll("(\\\\\\\\)+", "\\\\"));
Run Code Online (Sandbox Code Playgroud)

将输出

\\
\
Run Code Online (Sandbox Code Playgroud)

转义\正则表达式是反直觉的。