【问题标题】:System.getenv() returning \System.getenv() 返回 \
【发布时间】:2012-01-08 16:57:26
【问题描述】:

我正在尝试使用 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();

【问题讨论】:

  • “它在路径中返回一个 \ 而不是我需要的 /。” 如果环境返回一个路径的值,它将返回一个使用的值默认路径分隔符。为什么你需要改变它?顺便说一句 - 请修复您的换档键。这不是短信。

标签: java regex exec


【解决方案1】:

你需要把反斜杠加倍:

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

规范的正则表达式确实是\\,但在Java 中,正则表达式在字符串中,而在Java 字符串中,文字反斜杠需要用另一个反斜杠转义。因此\\ 变为"\\\\"

【讨论】:

  • 或者,如果您只想替换 字符 '\' 而不是弄乱正则表达式语法,请使用 .replace('\\', '/')
【解决方案2】:

在 Java 正则表达式中,您必须再次转义反斜杠和 Java 字符串。总共有四个反斜杠。

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

【讨论】:

    【解决方案3】:

    它在路径中返回一个 \ 而不是 / 这是我需要的。

    平台默认的肯定你需要的。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-16
      • 1970-01-01
      • 2012-11-03
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-29
      相关资源
      最近更新 更多