Java 替换“\\&引用;加上/&引用;在爪哇
我试图用java(Android)中的Java 替换“\\&引用;加上/&引用;在爪哇,java,android,replace,Java,Android,Replace,我试图用java(Android)中的'\\'替换'/',但这似乎不起作用 String rawPath = filePath.replace("\\\\", "/"); 这有什么问题?我已经转义了“\”并尝试转义“/”,但没有用。原始字符串没有任何变化 filePath = abc\\xyz(not after escaping two \\, the original string is with two \\) rawPath = abc \ xyz expect
'\\'
替换'/'
,但这似乎不起作用
String rawPath = filePath.replace("\\\\", "/");
这有什么问题?我已经转义了“\”并尝试转义“/”,但没有用。原始字符串没有任何变化
filePath = abc\\xyz(not after escaping two \\, the original string is with two \\)
rawPath = abc \ xyz
expected = abc/xyz
正确的做法是什么?(另一个Windows文件到Android路径转换问题)您不需要四重转义 \\\\ ,很简单 \\
.单斜杠转义就足够了。下面的对我来说很好
String rawPath=filePath.replace(“\\”,“/”
使用String.replace(String,String)
反斜杠不需要转义两次(这是在使用replaceAll
时-它处理regex)。因此:
或使用char
版本:
String rawPath = filePath.replace('\\', '/');
如果要用单个正斜杠替换原始字符串中由2个反斜杠组成的序列,应该可以:
String filePath = "abc\\\\xyz";
String rawPath = filePath.replace("\\\\", "/");
System.out.println(filePath);
System.out.println(rawPath);
产出:
abc\\xyz
abc/xyz
将打印
foo\\bar
foo/bar
你真的在字符串中有两个反斜杠吗?这只出现在Java源代码中。在运行时,只有一个反斜杠。因此,任务简化为将反斜杠改为正斜杠(为什么?)。如果您使用的是
replaceAll()
,则需要一个正则表达式,这需要四个正则表达式:两个用于编译器,两个用于正则表达式,但您没有使用它,而是使用的是replace()
,它不是正则表达式,因此您只需要两个正则表达式,一个用于编译器,另一个用于自身
你为什么这么做?在Java中,根本不需要在文件路径中使用反斜杠,也不需要将它们转换为/除非您正在使用它们执行类似URL的操作,在这种情况下有
File.toURI()
方法以及URI和URL类。这里有一个非常小的方法来获取桌面路径,并向您展示如何在return语句中替换它们
public static String getDesktopPath() {
String desktopPath = System.getProperty("user.home") + "/Desktop";
return desktopPath.replace("\\", "/");
}
反斜杠在java中总是需要转义的。这与正则表达式无关。您的建议将每个
\`替换为/`。字符串中的反斜杠始终需要在代码中转义,除非您打算将其用作其他转义序列的一部分。。。。当然是两次了。。。(这就是为什么我写了关于replaceAll
)的评论@dacwe我认为问题是基于给定的示例,用正斜杠替换字符串中由2个反斜杠组成的序列。我可能误解了。谢谢!基本上我得到的是,我从windows环境中得到一个字符串,格式是filepath=“abc\\xyz”
(只有两个“\\”),这就像一个魔咒,为什么不在整个代码中使用java.io.File.separator
!
foo\\bar
foo/bar
public static String getDesktopPath() {
String desktopPath = System.getProperty("user.home") + "/Desktop";
return desktopPath.replace("\\", "/");
}