簡體   English   中英

用單反斜杠替換雙反斜杠

[英]Replacing double backslash with single backslash

我有一個路徑(例如C:\\ Users \\ chloe \\ Documents),但是當我要將其保存在屬性文件中時,由於字符串“ C:\\ Users \\ chloe \\ Documents”,它會以雙斜杠保存它由於某些原因,它不會在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";

在用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("(\\\\\\\\)+", "\\\\"));

將輸出

\\
\

正則表達式中轉義\\是反直觀的。

path.replaceAll('\\',File.separator);

可能有效。 更多信息可能會有所幫助,例如如何獲取路徑以及它是什么類(正在讀取路徑或字符串的File路徑,還是逐段生成路徑)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM