System.getenv() 返回 \
我正在尝试使用 System.getenv 函数创建到计算机上某个位置的路径,它在路径中返回 \
而不是我需要的 /
。我尝试过使用 ReplaceAll 方法,但它返回一个错误:
Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.lang.String.replaceAll(Unknown Source)
at Launcher.start(Launcher.java:75)
at Launcher.Download(Launcher.java:55)
at Launcher.<init>(Launcher.java:31)
at Launcher.main(Launcher.java:17)
代码行是:
InputStream OS = Runtime.getRuntime().exec(new String[]{"java",System.getenv("APPDATA").replaceAll("\\", "/")+"/MS2-torsteinv/MS2-bin/no/torsteinv/MarsSettlement2/Client/Client.class"}).getErrorStream();
I'm trying to make a path to a place on the computer with the System.getenv function and it returns a \
in the path not a /
which is what I need. I have tried with the replaceAll method but it returns a error:
Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.lang.String.replaceAll(Unknown Source)
at Launcher.start(Launcher.java:75)
at Launcher.Download(Launcher.java:55)
at Launcher.<init>(Launcher.java:31)
at Launcher.main(Launcher.java:17)
the line of code is:
InputStream OS = Runtime.getRuntime().exec(new String[]{"java",System.getenv("APPDATA").replaceAll("\\", "/")+"/MS2-torsteinv/MS2-bin/no/torsteinv/MarsSettlement2/Client/Client.class"}).getErrorStream();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要加倍反斜杠:
规范的正则表达式确实是
\\
,但在 Java 正则表达式中位于字符串中,而在 Java 字符串中,需要用另一个反斜杠转义文字反斜杠。因此\\
变为"\\\\"
。You need to double the backslash:
The canonical regex is indeed
\\
, but in Java regexes are in strings, and in Java strings, a literal backslash needs to be escaped with another backslash. Hence\\
becomes"\\\\"
.在 Java 正则表达式中,您必须再次转义反斜杠,而在 Java 字符串中则必须再次转义。这总共有四个反斜杠。
In Java regular expressions you have to escape the backslash and in java string again. That makes in total four backslashes.
平台默认设置肯定就是您所需要的。
输出
The platform default sure is what you need.
Output