I am trying to add a registry key which will allow my program to start when my computer boots. It seems to not be working. Here is my code to do this:
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.
}
Here is my WinReg class:
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);
}
}
When printing cmdLine I get this:
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
I tried to manually run this command, but I couldn’t figure out the syntax error it was returning.
The reason
cmd /cdoesn’t work as present is because if the command has spaces, you must put it in quotes. If you want to usecmd /c, it is hard to format correctly, because of the nested quotes:The quotes with one set inside another confuse the interpreter.
But,
cmd /cis unnecessary: just run the command directly–Java runs the command as if you typed it into the command line. So, just type it like you would on the command line, as in the second code snippet above!!