Java System.getProperty ("user.home") 目录缺少分隔符

标签 java windows-8 registry home-directory

每当用户输入“~”作为参数时,我的程序都会将其替换为 System.getProperty("user.home")。

调试后,我发现这将“~”替换为“C:UsersSoulBeaver”,而不是“C:/Users/SoulBeaver”。

正在经历previous questions about incorrect user.home folders ,我发现Java尝试从

获取路径

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell 文件夹\

但是,我使用的是 Windows 8,似乎没有任何问题:

此时我假设 Java“吃掉”了反斜杠...那么我该如何防止这种情况发生呢?

更新

既然请求了代码,就放在这里。这取自 Allen Holub 的 Solving Java's Configuration Problem

/**
 * For every enum element in the array, treat keys[i].name() as a key
 * and load the associated value from the following places (in order):
 *
 * <ol>
 *     <li>a -D command-line switch (in System properties)</li>
 *     <li>if no -D value found, an environment variable with the same name as the key</li>
 *     <li>if no environment found, the default stored in the Enum element itself</li>
 * </ol>
 *
 * That value must identify an existing directory in the file system, and a
 * File representing that location can be retrieved from {@link #directory(Enum)}.
 *
 * @param keys The values() array associated with the enum that's using this class.
 * @throws IllegalStateException if a given key doesn't have a value associated with it
 *          or if that value doesn't identify an existing directory.
 */
public LocationsSupport(T[] keys) throws IllegalStateException {
    StringBuilder logMessage = new StringBuilder("Loaded environment/-D properties:\n");

    try {
        for (T element : keys) {
            String how = "???";
            String key = element.name();

            String value;
            if ((value = System.getProperty(key)) != null)
                how = "from system property (-D)";
            else if ((value = System.getenv(key)) != null)
                how = "from environment";
            else if ((value = element.defaultValue()) != null)
                how = "from default. Mapped from: " + value;

            if (value != null)
                value = value.replaceAll("~", System.getProperty("user.home"));

            if (value == null || value.isEmpty())
                throw new IllegalStateException("Value for " +key +" cannot be null or empty.");

            File location = new File(value);

            createLocationIfNecessary(location, element.createIfNecessary());

            if (!location.isDirectory())
                throw new IllegalStateException("Location specified in "
                        +key
                        +" (" +asString(location) +") "
                        +"does not exist or is not a directory.");


            dictionary.put(key, location);

            logMessage.append("\t");
            logMessage.append(key);
            logMessage.append("=");
            logMessage.append(asString(location) );
            logMessage.append(" (");
            logMessage.append(how);
            logMessage.append(")\n");
        }
    } finally {
        if (log.getAllAppenders() instanceof NullEnumeration)
            System.err.println(logMessage);
        else
            log.info(logMessage);
    }
}

尝试查找 CONFIG 的默认位置失败:

public enum Places implements Locations {
    CONFIG ("~/config"),
    HOME   ("~"),
    TMP    ("~/tmp", true),

    TERM_STORE     ("~/tmp/indices/term_store/",     true),
    RESOURCE_STORE ("~/tmp/indices/resource_store/", true),
    PERSON_STORE   ("~/tmp/indices/person_store/",   true);

我使用的是 Java 1.7.0_13IntelliJ IDEA 12.1.3

最佳答案

您正在使用基于正则表达式的替换。在 java 正则表达式的替换模式中,'\' 字符是特殊的。在将用户主目录用作替换模式之前,您需要通过 Matcher.quoteReplacement() 传递用户主目录(如 javadoc for the relevant method 中所述)。

关于Java System.getProperty ("user.home") 目录缺少分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16545885/

相关文章:

windows - 制作一个 .reg 文件以在右键菜单中添加快捷方式

visual-studio-2010 - 自定义操作不起作用 - Visual Studio 安装项目

java - 如何将连接字符串与 jdbc url 一起使用

java - 使用 FileChannels 在 Java 中连接大文件的方法更有效

xaml - Windows 8 Metro::什么是 AutomationProperties.AutomationId 和 AutomationProperties.Name

windows-8 - WinRT XAML 中的 RadialGradientBrush 在哪里?

java - 如何从 Java 代码访问 .bashrc 文件

java.lang.NumberFormatException : For input string: "20110328094108069414" 异常

c++ - Qt 中的 Qwizard 在窗口 8 上不显示完成和取消按钮,相同的代码在 7 上工作

c# - 如何在c#中为机器设置环境变量