我试图用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();发布于 2012-01-09 01:00:09
您需要将反斜杠加倍:
.replaceAll("\\\\", "/")规范的正则表达式确实是\\,但是在Java正则表达式是在字符串中,并且在Java字符串中,文字反斜杠需要用另一个反斜杠进行转义。因此,\\变成了"\\\\"。
发布于 2012-01-09 01:00:47
在Java正则表达式中,您必须转义反斜杠,然后在java字符串中再次转义。这使得总共有四个反斜杠。
replaceAll("\\\\", "/")发布于 2012-01-09 01:13:08
,它在路径中返回一个\,而不是我需要的/。
平台缺省设置确保是 what you need。
import java.io.File;
class FormPath {
public static void main(String[] args) {
String relPath = "/MS2-torsteinv/MS2-bin/no/" +
"torsteinv/MarsSettlement2/Client/Client.class";
String[] parts = relPath.split("/");
File f = new File(System.getenv("APPDATA"));
System.out.println(f + " exists: " + f.exists());
for (String part : parts) {
// use the File constructor that will insert the correct separator
f = new File(f,part);
}
System.out.println(f + " exists: " + f.exists());
}
}输出
C:\Users\Andrew\AppData\Roaming exists: true
C:\Users\Andrew\AppData\Roaming\MS2-torsteinv\MS2-bin\no\torsteinv\MarsSettlement2\Client\Client.class exists: false
Press any key to continue . . .https://stackoverflow.com/questions/8779363
复制相似问题