添加Windows注册表项不起作用

时间:2013-01-16 01:19:36

标签: java registry

我正在尝试添加一个注册表项,这将允许我的程序在我的计算机启动时启动。它似乎不起作用。这是我的代码:

String[] execArgs = new String [2];

if ( os.indexOf( "windows" ) > -1 ) {
    File source = Methods.getJar(); //This method simply returns the full path to the running jar file.
    URL url=null;
    url=source.toURL();  
    File f = new File( URLDecoder.decode( url.getFile(), "UTF-8" ) );
    String userDir = System.getProperty("user.home");
    String path ="" ;

    if ( os.indexOf( "7" ) > -1 ) {
        path = (userDir+"/AppData/Roaming/Microsoft/");
    }

    if ( os.indexOf( "vista" ) > -1 ){
        path = (userDir+"/AppData/Roaming/Microsoft/");
    }

    if ( os.indexOf( "xp" ) > -1 ){
        path = (userDir+"/Start Menu/Programs/Startup/");
    }

    path = path.replaceAll("%20"," ");
    System.out.println("Will copy file to " +path);
    File targetDir = new File(path);
    FileUtils.copyFileToDirectory(f, targetDir);//Copy the file to appdata/roaming dir.
    String filename = source.getName();
    int last = filename.lastIndexOf("\\");
    filename = filename.substring(last + 1);
    String fullPath = path+filename;
    int l1 = filename.lastIndexOf(".");
    String fileText = filename.substring(0,l1);
    execArgs[0] = fileText;
    execArgs[1] = fullPath;
    new WinReg().exec(execArgs);  //Add a reg key to add to startup using WinReg class.
}

这是我的WinReg课程:

package test;
import java.text.MessageFormat;  

public class WinReg {  
    static final String REG_ADD_CMD = "cmd /c reg add \"HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Run\" /v \"{0}\" /d \"{1}\" /t REG_EXPAND_SZ";  

    void exec(String[] args)throws Exception {  
        if (args.length != 2)  
            throw new IllegalArgumentException("\n\nUsage: java SetEnv {key} {value}\n\n");  

        String key = args[0];  
        String value = args[1];  

        String cmdLine = MessageFormat.format(REG_ADD_CMD, new Object[] { key, value });  
        System.out.println(cmdLine); //get the final cmd that will be run
        Runtime.getRuntime().exec(cmdLine);  
    }  
}  

打印cmdLine时,我明白了:

cmd /c reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\Curren
tVersion\Run" /v "Test" /d "C:\Users\CJ/AppData/Roaming/Microsoft/Test.jar" /t R
EG_EXPAND_SZ

我尝试手动运行此命令,但我无法弄清楚它返回的语法错误。

1 个答案:

答案 0 :(得分:1)

cmd /c无效的原因是因为如果命令有空格,则必须将其放在引号中。如果您想使用cmd /c,由于嵌套引号,很难正确格式化:

rem Does not work:
cmd /c "reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run" /v "Test" /d "C:\Users\CJ/AppData/Roaming/Microsoft/Test.jar" /t REG_EXPAND_SZ"

另一组内部引号混淆了解释器。

但是,cmd /c是不必要的:只需直接运行命令 -

reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Run" /v "Test" /d "C:\Users\CJ/AppData/Roaming/Microsoft/Test.jar" /t REG_EXPAND_SZ

Java运行命令,就像在命令行中输入命令一样。所以,只需在命令行中输入就像在上面的第二个代码片段中那样输入!!