用单反斜杠替换双反斜杠

时间:2017-03-18 15:49:52

标签: java file path

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

path.replaceAll("/+", "/");

但是这取代了正常的斜杠,我想知道如何使用反斜杠...(在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";

2 个答案:

答案 0 :(得分:5)

\\字面值中对其进行硬编码时,只需要String。由于\转义字符,因此它在运行时变为单个\。您还可以使用/作为分隔符编写路径。要清楚

String path = "C:\\Users\\chloe\\Documents";

创建一个String,其值等于C:\Users\chloe\Documents(如果您要print它)。你也可以写

String path = System.getProperty("user.home") + File.separator + "Documents";

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

System.out.println("\\\\");
System.out.println("\\\\".replaceAll("(\\\\\\\\)+", "\\\\"));

将输出

\\
\

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

答案 1 :(得分:-1)

if (empty($value) or strlen($value) == 0 or $value == 0)

可能会奏效。更多信息可能会有所帮助,例如您如何获取路径以及它是什么类(您正在读取路径或字符串的文件路径,是否正在逐段生成路径)。

相关问题