简体   繁体   English

System.getenv() 返回 \\

[英]System.getenv() returning \

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.我试图做一个路径,计算机与System.getenv功能上占有一席之地,它返回一个\\路径不是/这正是我需要的。 I have tried with the replaceAll method but it returns a error:我尝试过使用 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)

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();

You need to double the backslash:您需要将反斜杠加倍:

.replaceAll("\\\\", "/")

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.规范的正则表达式确实是\\\\ ,但在 Java 正则表达式中是字符串,而在 Java 字符串中,文字反斜杠需要用另一个反斜杠转义。 Hence \\\\ becomes "\\\\\\\\" .因此\\\\变为"\\\\\\\\"

In Java regular expressions you have to escape the backslash and in java string again.在 Java 正则表达式中,您必须再次转义反斜杠和 java 字符串。 That makes in total four backslashes.这总共有四个反斜杠。

replaceAll("\\\\", "/")

it returns a \\ in the path not a / wich is what i need.它在路径中返回一个 \\ 而不是我需要的 / 。

The platform default sure is 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());
    }
}

Output输出

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 . . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM