[英]How to escape the backslashes and the automatically generated escape character in file path in java
[英]How to get File Path with double-backslashes in Java
我有一個程序,可以將學校成績保存在 .txt 文件中。 我想讓用戶選擇應該保存這個文件的位置。 它適用於 JFileChooser 查找,但 Java 的 FilePath 有問題。 JFileChooser 的文件路徑如下所示: C:\\Users...\\Documents\\n.txt 但是如果我想讀取程序中的 TextFile,Java 說它找不到文件路徑。 它應該是這樣的: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);
}
這不起作用它說無效的字符常量
在某些地方,反斜杠用作轉義字符,並且必須進行轉義,僅作為 Windows 路徑分隔符的反斜杠。
這些地方在 .properties 文件、java 字符串文字等中。
對於 Windows 路徑,您也可以使用斜杠(Windows 的 POSIX 合規性)。
fPath = fPath.replace('\\', '/');
反斜杠:
fPath = fPath.replace("\\", "\\\\");
解釋是必須對 char 和 string 文字中的單個反斜杠進行轉義:兩個反斜杠代表一個反斜杠。
對於正則表達式 (replaceAll),使用反沖作為命令:數字表示為\\d
和 java String: "\\\\d"
。 因此反斜杠本身變成(看):
fPath = fPath.replaceAll("\\\\", "\\\\\\\\"); // PLEASE NOT
我幾乎沒有看到它,但是 String 上的方法不會改變它,而是返回一個新值,因此需要分配結果。
在 Java 中使用硬編碼文件名時,應始終使用正斜杠/
作為文件分隔符。 Java 知道如何在 Windows 上處理它們。
你也不應該使用絕對路徑。 您不知道目標系統中是否存在該路徑。 您應該使用以類路徑開頭的相對路徑作為根“/...”,或者從System.getProperty()
https://docs.oracle.com/javase/8/docs/api/java/獲取一些系統相關的位置lang/System.html#getProperties--
您的代碼中存在多個問題:
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
返回的路徑。
在 Java 中您不需要帶有雙反斜杠的文件路徑。 雙反斜杠用於:
在其他任何地方,您都可以獲得反斜杠,或使用正斜杠。
可能您正在尋找java.util.Properties
嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.